python - 如何在不转换为列表的情况下替换 python 字符串中特定位置的字母?

标签 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)
                answer = answer.replace(answer[location],userInput)
        print(answer)

当前输出:

iiiiiiiiii

期望的输出:

**i****i**

最佳答案

什么 x.replace(a, b)确实是替换任何出现的值 axb所以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/

相关文章:

jquery 无法从 CDN 与 django 模板一起工作

python - FindContours 仅支持 8uC1 和 32sC1 图像

python - Pytorch张量形状

python - 基于大量此类短语替换大文本文件中的短语的省时方法

vim - 将命令行的输出写入vim中的文件

python - 如何在 python 中导入 Tensorflow 库?

c - 没有字符串数组的输出

c++ - 为什么字符串文字上的 decltype 不产生数组类型?

c++ - std::string 作为映射键和 map.find() 的效率

regex - 使用 vim 替换出现次数可变的不匹配字符串