您好,欢迎访问一九零五行业门户网

如何在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 iomystr = hello, how are you?print(string = ,mystr)# stringio is a text stream using an in-memory text bufferstrio = io.stringio(mystr)# the getvalue() returns a string containing the entire contents of the bufferprint(strio.getvalue())
outputstring = hello, how are you?hello, how are you?
现在,让我们改变流的位置,写入新内容并显示
change the stream position and write new stringexample的中文翻译为:示例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 iomystr = hello, how are you?# stringio is a text stream using an in-memory text bufferstrio = io.stringio(mystr)# the getvalue() returns a string containing the entire contents of the bufferprint(string = ,strio.getvalue())# change the stream position using seek()strio.seek(7)# write at the same positionstrio.write(how's life?)# returning the final stringprint(final string = ,strio.getvalue())
outputstring = hello, how are you?final string = hello, how's life
create an array and convert it to unicode stringexample的中文翻译为:示例在这个例子中,使用array()创建一个数组,然后使用tounicode()方法将其转换为unicode字符串 -
import array# create a stringmystr = hello, how are you?# arrayarr = array.array('u',mystr)print(arr)# modifying the arrayarr[0] = 'm'# displaying the arrayprint(arr)# convert an array to a unicode string using tounicodeprint(arr.tounicode())
outputarray('u', 'hello, how are you?')array('u', 'mello, how are you?')mello, how are you?
以上就是如何在python中就地修改字符串?的详细内容。
其它类似信息

推荐信息