Home > Article > Backend Development > How to modify a string in-place in Python?
Unfortunately, you cannot modify the string in place because strings are immutable. Just create a new string from the few parts you want to collect. However, if you still need an object that can modify Unicode data in-place, you should use
Let’s see what we discussed above −
In this example, we will return a string with the entire contents of the buffer. We have a text stream StringIO −
import io myStr = "Hello, How are you?" print("String = ",myStr) # StringIO is a text stream using an in-memory text buffer strIO = io.StringIO(myStr) # The getvalue() returns a string containing the entire contents of the buffer print(strIO.getvalue())
String = Hello, How are you? Hello, How are you?
Now, let's change the position of the stream, write new content and display
We will see another example and change the stream position using the seek() method. A new string will be written at the same position using the write() method −
import io myStr = "Hello, How are you?" # StringIO is a text stream using an in-memory text buffer strIO = io.StringIO(myStr) # The getvalue() returns a string containing the entire contents of the buffer print("String = ",strIO.getvalue()) # Change the stream position using seek() strIO.seek(7) # Write at the same position strIO.write("How's life?") # Returning the final string print("Final String = ",strIO.getvalue())
String = Hello, How are you? Final String = Hello, How's life??
In this example, use array() to create an array, and then use the tounicode() method to convert it to a Unicode string -
import array # Create a String myStr = "Hello, How are you?" # Array arr = array.array('u',myStr) print(arr) # Modifying the array arr[0] = 'm' # Displaying the array print(arr) # convert an array to a unicode string using tounicode print(arr.tounicode())
array('u', 'Hello, How are you?') array('u', 'mello, How are you?') mello, How are you?
The above is the detailed content of How to modify a string in-place in Python?. For more information, please follow other related articles on the PHP Chinese website!