2024-10-02 00:42:18 发布
网友
我尝试过使用.replace(),但当我使用索引定义被替换的字符时,它会替换所有与被索引字符相同的字符,如下所示:
string = "cool" print(string.replace(string[1], "u"))
如果返回:
"cuul"
但我只想替换字符串[1]的索引所对应的特定字符,例如,我希望它可以这样工作:
string = "cool" print(substitute(string[1],"u")
以便打印:
"cuol"
您试图做的是搜索string[1],它是o,并将o的所有实例替换为u
string[1]
o
u
string = "cool" print(string.replace(string[1], "u")) # cuul
问题是字符串对象是immutable,因此您只需创建一个新字符串,其中包含所需索引处的值
immutable
index = 1 char = 'u' print(string[:index] + char + string[index+1:]) #cuol
def substitute(string,index,char): strlist = list(string) strlist[index] = char return ''.join(strlist)
这应该起作用:
stirng1 = "cool" list1 = list(string1) list1[1] = "u" print("".join(list1))
执行时:
>>>cuol
您试图做的是搜索
string[1]
,它是o
,并将o
的所有实例替换为u
问题是字符串对象是
immutable
,因此您只需创建一个新字符串,其中包含所需索引处的值这应该起作用:
执行时:
相关问题 更多 >
编程相关推荐