如何让我的程序检查一个单词中的多个字母

时间:2014-10-25 17:12:33

标签: string list python-3.x indexing position

我这里有一个程序,它应该检查用户输入,与实际单词进行比较,并打印出用户找到的实际单词的数量。但是,当用户输入一个在单词中出现多次的字母时,我的问题就出现了。

position = []
word = "elephant"
letter = input("Please enter a letter: ")

for letter in word:
    position.append("_")
if letter in word:
    position[word.index(letter)] = letter
    print("".join(position))

在这种情况下,如果我输入了" e"虽然我想要的是e_e____,但程序会输出e_______。谢谢。

1 个答案:

答案 0 :(得分:0)

签入for循环:

for char in word: # don't use 'letter' again
    if char == letter:
        position.append(char)
    else:
        position.append('_')

作为列表理解:

position = [char if char == letter else '_' for char in word]