首页 > 解决方案 > 如何打印包含特定字母的单词

问题描述

我有单词文件,每行包含一个单词。我尝试做的是向用户询问字母并搜索用户输入的所有这些字母的单词。我工作了几天,但无法使第 7 行和第 8 行正常运行,只会出现不同的错误,或者没有给出任何结果。

letters = input('letters: ')
words = open('thesewords').read().splitlines()

print (words)
print(".......................")

for word in words:
    if all(letters) in word:
        print(word)

标签: pythonpython-3.x

解决方案


你用all()错了。 all(letters)始终是Truefor string letters,并True in <string>返回一个TypeError.

你应该做的是:

all(x in word for x in letters)

所以,它变成:

for word in words:
    if all(x in word for x in letters):
        print(word)

推荐阅读