Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.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_Input - Fatal编程技术网

如何识别单词中的字符并将该字母替换为另一个字符串-Python

如何识别单词中的字符并将该字母替换为另一个字符串-Python,python,string,input,Python,String,Input,对于我的刽子手项目,在这个人猜对了一个字母的情况下,我希望能够用这个字母来代替一个“u”空格 word = input('Please enter a word for your opponent:') letter = input('Enter a letter to try and guess the word:') print('_ '*len(word)) if 'a' in word and letter: print('_ '*len(word) with 'a' in

对于我的刽子手项目,在这个人猜对了一个字母的情况下,我希望能够用这个字母来代替一个“u”空格

word = input('Please enter a word for your opponent:')

letter = input('Enter a letter to try and guess the word:')

print('_ '*len(word))

if 'a' in word and letter:
    print('_ '*len(word) with 'a' in word)

例如,如果输入的单词是“matt”,则输出将是
“\u a\u”
,您可以将正则表达式替换为
re.sub

In [514]: word = 'matt'

In [515]: letter = 'a'

In [518]: re.sub(r'[^%s]' %letter, '_', word)
Out[518]: '_a__'

作为如何在后续字母中继续使用此方法的提示,每次用户输入字母时,将其添加到
字母
,如下所示:

In [521]: new_letter = 't' # replace this with user input

In [522]: letter += new_letter
并且,regex将在适当地显示以下内容时处理新字母:

In [523]: re.sub(r'[^%s]' %letter, '_', word)
Out[523]: '_att'

您可以将正则表达式替换与
re.sub
一起使用:

In [514]: word = 'matt'

In [515]: letter = 'a'

In [518]: re.sub(r'[^%s]' %letter, '_', word)
Out[518]: '_a__'

作为如何在后续字母中继续使用此方法的提示,每次用户输入字母时,将其添加到
字母
,如下所示:

In [521]: new_letter = 't' # replace this with user input

In [522]: letter += new_letter
并且,regex将在适当地显示以下内容时处理新字母:

In [523]: re.sub(r'[^%s]' %letter, '_', word)
Out[523]: '_att'

您也可以用一种更简单的方法来实现这一点

>>> word_split = list(word)
>>> for a in range(len(word_split)):
...     if word_split[a] != letter:
...             word_split[a] = "_"
... 
>>> print(" ".join(word_split))
_ _ _ _ _ _ _ a _

然而,@COLDSPEED的解决方案非常优雅

您也可以用一种更简单的方法来实现这一点

>>> word_split = list(word)
>>> for a in range(len(word_split)):
...     if word_split[a] != letter:
...             word_split[a] = "_"
... 
>>> print(" ".join(word_split))
_ _ _ _ _ _ _ a _

然而,@COLDSPEED的解决方案非常优雅

这里是另一个非正则表达式的解决方案。在找到给定字符的位置创建一组标记。然后,它用于索引可以在传入的下划线列表中替换的字符(一种更新主游戏循环中传递的序列引用的方法)

样本输出:

>>> s = "matt"
>>> l = ["_" for _ in range(len(s))]
>>> print subsitute_character("t", s, l)
__tt

这是另一个非正则表达式的解决方案。在找到给定字符的位置创建一组标记。然后,它用于索引可以在传入的下划线列表中替换的字符(一种更新主游戏循环中传递的序列引用的方法)

样本输出:

>>> s = "matt"
>>> l = ["_" for _ in range(len(s))]
>>> print subsitute_character("t", s, l)
__tt
print('''.join(c if c in gusted else''for c in word))
将为每个字母打印空白,但
gusted
中的字母除外。看看你是否可以用它来解决剩下的问题。
print('''.join(c if c in gusted else'.'for c in word))
将为每个字母打印空白,除了
gusted
中的字母。看看你是否可以用它来解决剩下的问题。