简体   繁体   English

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

[英]How to identify a character within a word and substitute that letter into another string - Python

For my hangman project, in the situation that the person does guess a letter correctly, I want to be able to substitute that letter in for a '_' space. 对于我的子手项目,在此人确实正确猜出字母的情况下,我希望能够用该字母代替'_'空格。

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)

For example if the word entered was 'matt,' the output would be '_a__' 例如,如果输入的单词是'matt',则输出将是'_a__'

You can use regex substitution with re.sub : 您可以将regex替换与re.sub

In [514]: word = 'matt'

In [515]: letter = 'a'

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

As a tip on how to continue with this approach with subsequent letters, each time the user inputs a letter, add it to letter , like this: 作为有关如何继续使用后续字母的方法的提示,每次用户输入字母时,将其添加到letter ,如下所示:

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

In [522]: letter += new_letter

And, regex will handle the new letter when displaying, appropriately: 并且,正则表达式将在显示时适当地处理新字母:

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

You can also do this in a much simpler way. 您也可以以更简单的方式执行此操作。

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

However @COLDSPEED 's solution is an elegant one. 但是@COLDSPEED的解决方案是一种优雅的解决方案。

Here's another non-regex solution. 这是另一个非正则表达式解决方案。 Creates a set of indicies where the given character was found. 创建一组找到给定字符的索引。 That is then used to index characters that can be replaced in the list of underscores that's passed in ( one approach to update the passed sequence reference in your main game loop ). 然后,该索引用于索引可以在传入的下划线列表中替换的角色( 一种在主游戏循环中更新所传递的序列引用的方法 )。

def subsitute_character(character, target_word, sequence):
    indicies = {index for index, element in enumerate(target_word) if element == character}
    return ''.join(target_word[index] if index in indicies else element 
        for index, element in enumerate(sequence))

Sample Output: 样本输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM