很不幸,您无法原地修改字符串,因为字符串是不可变的。只需从您想要收集的几个部分创建一个新的字符串。但是,如果您仍然需要一个能够原地修改Unicode数据的对象,您应该使用
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?
现在,让我们改变流的位置,写入新内容并显示
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??
在这个例子中,使用array()创建一个数组,然后使用tounicode()方法将其转换为Unicode字符串 -
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?
以上是如何在Python中就地修改字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!