替换python 3.0中字符串的某个索引

替换python 3.0中字符串的某个索引,python,string,Python,String,我需要替换字符串中的一个字符,但这里有一个问题,字符串将全部是下划线,我需要能够替换与单词索引对应的下划线。例如: 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 = '___'
word = 'cow'
guess = input('Input the your letter guess') #user inputs the letter o for example
if guess in word:
    underscore = underscore.replace('_',guess)
>>> "bananaphone".index("p")
6
>>> "bananaphone"[:6]
'banana'
>>> "bananaphone"[7:]
'hone'
>>> "bananaphone"[:6] + "x" + "bananaphone"[7:]
'bananaxhone'

我需要修正的是,被替换的下划线必须位于三个下划线中的第二位。我不想要下划线='o_uuu',而是想要
'o_uuu'

你只需要从
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
函数逐字符迭代
单词
,每次迭代时,当前字符将位于
char
变量中。然后,我们决定在结果字符串中用什么来代替当前字符

'_' if char != guess else char

这意味着,如果当前字符与猜测的字符不相等,则使用
\uuu
,否则按原样使用字符。最后,所有这些字符都与
”连接在一起。连接

您只需从
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
函数逐字符迭代
单词
,每次迭代时,当前字符将位于
char
变量中。然后,我们决定在结果字符串中用什么来代替当前字符

'_' if char != guess else char

这意味着,如果当前字符与猜测的字符不相等,则使用
\uuu
,否则按原样使用字符。最后,所有这些字符都用
”连接在一起。你不能改变它们。你只能重新定义它们

一个简单的方法是找到相关字母的索引:

index = "cow".index("o")
然后使用切片表示法从单词中提取所需的其余部分:

newword = word[:index] + yourletterhere + word[index+1:]
例如:

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)
>>> "bananaphone".index("p")
6
>>> "bananaphone"[:6]
'banana'
>>> "bananaphone"[7:]
'hone'
>>> "bananaphone"[:6] + "x" + "bananaphone"[7:]
'bananaxhone'

Python中的字符串是不可变的。你不能改变它们。你只能重新定义它们

一个简单的方法是找到相关字母的索引:

index = "cow".index("o")
然后使用切片表示法从单词中提取所需的其余部分:

newword = word[:index] + yourletterhere + word[index+1:]
例如:

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)
>>> "bananaphone".index("p")
6
>>> "bananaphone"[:6]
'banana'
>>> "bananaphone"[7:]
'hone'
>>> "bananaphone"[:6] + "x" + "bananaphone"[7:]
'bananaxhone'

如果字符串是不可变的,那么为什么我们可以对它们使用替换?替换重新定义字符串。你正在用一个新字符串覆盖旧字符串。I字符串是不可变的,那么我们怎么可以对它们使用替换?替换重新定义字符串。你正在用一个新的覆盖旧的。这很漂亮,非常感谢!我显然采取了错误的方法,试图处理一串下划线,而正确的方法(如果我理解正确的话,你就是这样做的)是使用这个词并用下划线围绕它。这很漂亮,非常感谢!很明显,我采取了错误的方法,试图处理一串下划线,而正确的方法(如果我理解正确的话,你就是这样做的)是使用这个词并在它周围加下划线