首頁 >後端開發 >Python教學 >如何在Python中就地修改字串?

如何在Python中就地修改字串?

WBOY
WBOY轉載
2023-08-20 18:53:161472瀏覽

如何在Python中就地修改字串?

很不幸,您無法原地修改字串,因為字串是不可變的。只需從您想要收集的幾個部分創建一個新的字串。但是,如果您仍然需要一個能夠原地修改Unicode資料的對象,您應該使用

  • io.StringIO物件
  • 數組模組

Let’s see what we discussed above −

傳回一個包含緩衝區全部內容的字串

Example

的中文翻譯為:

範例

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())

Output

#
String = Hello, How are you?
Hello, How are you?

現在,讓我們改變流的位置,寫入新內容並顯示

Change the stream position and write new String

Example

的中文翻譯為:

範例

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())

Output

#
String = Hello, How are you?
Final String = Hello, How's life??

Create an array and convert it to Unicode string

Example

的中文翻譯為:

範例

在這個範例中,使用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())

Output

#
array('u', 'Hello, How are you?')
array('u', 'mello, How are you?')
mello, How are you?

以上是如何在Python中就地修改字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除

相關文章

看更多