In python, string objects are immutable types, so we cannot directly modify a certain character in it like other languages. So essentially, changing the element of a string is to create a new string. We can modify it using the following method:
The first method:
First, convert the string into a list object, then modify it according to the nature of the list, and finally use the join function to create the modified string.
Specific usage examples are as follows:
s='12345' l=list(s) l[2]='a' s=''.join(l) print(s)
The second method:
Use the replace function of the string:
Specific usage examples are as follows:
s='abcdef' s=('a','1') print(s)
The third method:
By splicing between strings:
Examples of use are as follows:
s='I from' c=' China.' s=s+c print(s)
The above methods can all achieve the effect of modifying strings, but when we are actually using them, we may need to combine these methods to achieve the effect we want.
This is the end of this article about three methods of modifying string values in python. For more related contents of modifying string values in python, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!