字符串不可按索引赋值修改,以下是目前掌握修改字符串的方式:
原句子:I think i can make it.
要求改成:I sware i can make it.
方式1:使用replace替换
s = "i think i can make it" print(s.replace("think","swear"))方式2:使用切片的方式进行替换,本质是拼接字符串
s = "i think i can make it" print(s[:2] + "swear" + s[7:])方式3:使用io.StingIO,构造实例化流对象,创建子类实例,对文本进行操作。
import io s = "i think i can make it" NewS = io.StringIO(s) print(NewS.getvalue()) NewS.seek(2) NewS.write("swear") print(NewS.getvalue())方式4:使用列表,获取字符,挨个替换,本质是拼接字符串
s = "i think i can make it" lst = list(s) # 复制成可改的列表,原s不动 print(lst) lst[2] = "s" lst[3] = "w" lst[4] = "e" lst[5] = "a" lst[6] = "r" s = "".join(lst) # 再拼回新字符串 print(s)