Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,如何替换字符串中特定位置的字母,而不转换为列表?_Python_String_Replace_Python 3.2 - Fatal编程技术网

在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
so
answer.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:]