在python中,如何替换字符串中特定位置的字母,而不转换为列表?
我想替换字符串上的特定位置,但它正在替换整个字符串 守则的有关部分:在python中,如何替换字符串中特定位置的字母,而不转换为列表?,python,string,replace,python-3.2,Python,String,Replace,Python 3.2,我想替换字符串上的特定位置,但它正在替换整个字符串 守则的有关部分: userInput = "i" word = "university" answer = "*" * len(word) if userInput in word: for letter in word: if letter == userInput: location = word.find(userInput) ans
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)
所做的是将x
中出现的a
值替换为b
soanswer.replace(answer[location],userInput)
只是将所有*
值替换为userInput
,因为答案[location]
是*
。换句话说,不可能像那样指定要替换的内容的索引
因此,不是:
answer = answer.replace(answer[location],userInput)
做
更新:
其余的逻辑也有缺陷,因此这将起作用:
userInput = "i"
word = "university"
answer = "*" * len(word)
for location, letter in enumerate(word):
if letter == userInput:
answer = answer[:location] + userInput + answer[location + 1:]
这还包含使用SethMMorton的enumerate()
的建议,这是不可避免的:)
enumerate('abc')
将产生[(0,'a'),(1,'b'),(2,'c')]
,这意味着您不需要使用find
,因为您已经可以立即获得字母的位置(索引)。看起来您想用“*”替换所有不是userInput
的字符。对吗?所有字符都是*,但我想替换word中包含的用户输入,就像一个刽子手游戏,如果您可以看到您猜对的字母,那么如果建议在for
循环中使用enumerate
来获取位置
,而不是使用word
的find
方法,这个答案会有很大的改进。一般来说,是的,但是我认为OP正在为编程/Python的基础知识而挣扎,所以我认为在他理解x.replace(a,b)
的意思之前建议对他的程序进行彻底的修改不是一个好主意。我不确定这是否是一次彻底的修改。。。这将是修改一行,删除另一行。此外,find
不会只定位第一个实例,所以在这种情况下,enumerate
会更正确吗?最后,注意假设OP的性别…啊,是的,你的逻辑的另一部分是错误的。。。让我来解决这个问题@塞斯莫顿:对不起,我没有注意。我添加了一个带有枚举的答案(这是正确的答案),但是你修改了你的答案,就像我添加了我的一样,所以本着良好的精神,我删除了我的,并对你的进行了投票。
userInput = "i"
word = "university"
answer = "*" * len(word)
for location, letter in enumerate(word):
if letter == userInput:
answer = answer[:location] + userInput + answer[location + 1:]