我想替换字符串上的特定位置,但它正在替换整个字符串
相关部分代码:
userInput = "i"
word = "university"
answer = "*" * len(word)
if userInput in word:
for letter in word:
if letter == userInput:
location = word.find(userInput)
answer = answer.replace(answer[location],userInput)
print(answer)
当前输出:
iiiiiiiiii
期望的输出:
**i****i**
请您参考如下方法:
什么 x.replace(a, b)确实是替换任何出现的值 a在 x与 b所以answer.replace(answer[location], userInput)只是替换所有 *值为 userInput因为answer[location]是* .换句话说,不可能像那样指定要替换的内容的索引。
所以代替:
answer = answer.replace(answer[location],userInput)
做
answer = answer[:location] + userInput + answer[location + 1:]
更新:
其余的逻辑也有缺陷,所以这会起作用:
userInput = "i"
word = "university"
answer = "*" * len(word)
for location, letter in enumerate(word):
if letter == userInput:
answer = answer[:location] + userInput + answer[location + 1:]
这还包含使用 enumerate() 的建议由 SethMMorton 设计,结果证明这是不可避免的 :)
enumerate('abc')将产生 [(0, 'a'), (1, 'b'), (2, 'c')] ,这意味着您不需要使用 find因为您已经可以立即获得这封信的位置(索引)。
