很不幸,您無法原地修改字串,因為字串是不可變的。只需從您想要收集的幾個部分創建一個新的字串。但是,如果您仍然需要一個能夠原地修改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中文網其他相關文章!