我需要替换字符串中的一个字符,但这里有一个问题,字符串将全部是下划线,我需要能够替换与单词索引对应的下划线。例如:
underscore = '___'
word = 'cow'
guess = input('Input the your letter guess') #user inputs the letter o for example
if guess in word:
underscore = underscore.replace('_',guess)
我需要修复的是被替换的下划线需要在三个下划线的第二位。我不想 underscore = 'o__'
而是 '_o_'
最佳答案
你只需要从 word
中排除所有其他字符,并像这样形成一个新字符串
def replacer(word, guess):
return "".join('_' if char != guess else char for char in word)
assert(replacer("cow", "o") == "_o_")
即使猜测的字符多次出现,这也会起作用
assert(replacer("bannana", "n") == "__nn_n_")
replacer
函数逐个字符迭代word
,在每次迭代中,当前字符将在char
变量中。然后,我们决定用什么来代替当前字符,在结果字符串中用
'_' if char != guess else char
这意味着,如果当前字符不等于猜测的字符,则使用 _
否则按原样使用该字符。最后,所有这些字符都通过 "".join
连接在一起。
关于python - 在python 3.0中替换字符串的某个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26374484/