在Python中,字符串属于不可变对象,不支持原地修改,如果需要修改其中的值,只能重新创建一个新的字符串对象。
然而,如果确实需要一个支持原地修改的unicode数据对象,可以使用io.StringIO对象或array模块.
代码如下:
from io import StringIO a = "hello world" # 创建可变字符串对象 sio = StringIO(a) print(sio) # <_io.StringIO object at 0x00000227F03090D8> print(sio.tell()) # 获取当前文件读取指针的位置 print(sio.read()) # 从当前位置开始读取字符串 # hello world print(sio.getvalue()) # 返回可变字符串的全部内容 # hello world print(sio.tell()) # 11 sio.seek(6) # 用于移动文件读写指针到指定位置 【可以重新定位指针的位置】 sio.write("<a href="https://www.gaodaima.com/tag/python" title="查看更多关于python的文章" target="_blank">python</a>") # 从seek(6)指定的位置开始写入字符串 print(sio.getvalue()) # hello python```
www#gaodaima.com来源[email protected]搞@^&代*@码)网搞代码
来源:搞代码网:原文地址:https://www.gaodaima.com