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

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

不幸的是,您无法直接就地修改字符串,因为字符串是不可变的。只需从您想要从中收集的几个部分创建新字符串即可。不过,如果您仍需要能够修改就地 unicode 数据的对象,则应选择

  • io.StringIO 对象
  • 数组模块

让我们看看上面讨论的−

返回缓冲区的整个内容的字符串

示例

在这个示例中,我们将返回带有缓冲区的整个内容的字符串。我们有一个文本流 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 字符串

示例

在此示例中,使用数组() 创建数组,然后使用 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教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程