我想替换字符串上的特定位置,但它正在替换整个字符串
相关部分代码:
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
因为您已经可以立即获得这封信的位置(索引)。
关于python - 如何在不转换为列表的情况下替换 python 字符串中特定位置的字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232914/