如何在 Python 中就地修改字串?
不幸的是,您不能就地修改字串,因為字串是不可變的。只需從您想要從中收集的幾個部分建立一個新字串即可。但是,如果您仍然需要一個能夠就地修改 Unicode 資料的物件,則應使用
- io.StringIO 物件
- Array 模組
讓我們看看上面討論的內容 -
返回包含緩衝區全部內容的字串
示例
在此示例中,我們將返回包含緩衝區全部內容的字串。我們有一個文字流 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?
現在,讓我們更改流位置,寫入新內容並顯示
更改流位置並寫入新字串
示例
我們將看到另一個示例,並使用 seek() 方法更改流位置。使用 write() 方法將在相同位置寫入新字串 -
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??
建立陣列並將其轉換為 Unicode 字串
示例
在此示例中,使用 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?
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP