def replace_at_index(string, index):
print (string.replace(string[index], "-", 1))
这是我用给定索引替换字符的当前代码。
"Hous-e"
。
不知道它为什么要这么做。我想要的结果是它取代给定的指数,在“侯赛”指数5的情况下,该指数将是"House-“
发布于 2021-03-11 19:53:50
这是一次黑客攻击,但有效:
def replace_at_index(string, index):
ls = list(string)
ls[index] = "-"
s = "".join(ls)
print(s)
发布于 2021-03-11 19:50:35
替换方法将替换字符串中的给定子字符串。
代码所做的是替换字符串中字符的第一次出现。
相反,你应该做的是:
def replace_at_index(string, index):
new_string = string[:index]
new_string += "-"
new_string += string[index+1:]
return new_string
(以琵琶的方式;)
发布于 2021-03-11 19:50:49
str.replace
不是替换索引,而是值的第一次出现。因为"Housee"[5] == 'e'
,它将取代第一个'e'
def replace_at_index(string, index):
newstr = string[:index] + '-' + string[index+1:]
return newstr
https://stackoverflow.com/questions/66589489
复制相似问题