Demo
info = ' ABC '
If you want to replace the C in the above string info with D, how do I do it?
Method One: Use the Replace () method in Python
Grammar:
Str. Replace(old, new[, Max])
Parameters:
- Old--the substring to be replaced.
- New-A string that replaces the old substring.
- Max--Optional string, replace no more than Max Times
" ABC ">>> str = info.replace ("C","D")
Print (str)
'abd'
This approach is done by assigning a data object to a new variable to achieve the effect of the substitution.
Method Two: Use the list () method to convert the type of the string into a list type that can be changed, and then use the "". Join () method to combine the results into a string
" ABC ">>> b = list (info)"D"" ". Join (b)print (info) Abd
It is important to note that in Python, the string data type is immutable, and when the data object is assigned to a variable, the variable is actually a reference to the object, not the value of the object. So the above method changes the string members by assigning them to a new variable. Gets a reference to the changed value by generating a new variable.
Modify the value of a string in Python