如果一个单词包含特定字母,如何打印出来?
我怎么才能打印出一个列表或字符串中包含特定字母的单词呢?
比如:
字母:e
输入:我需要帮助我的程序
需要帮助
你看,它打印出了“需要帮助”,因为这些词里都有“e”这个字母,对吧?希望能帮到你 :)
我的解决方法:
a = input("Letter: ")
b = input("Input: ")
c = b.count(a)
print(c)
d = b.split()
for e in d:
print(e,end=" ")
3 个回答
0
你可以用 in
来检查一个字符(或者一段文字)是否在一个字符串里:
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
for word in words:
if letter in word:
print(word, end=" ")
print() # Add newline
补充说明(见评论):
要去掉最后的空格,你可以把单词放在一个字符串里,然后再去掉它。
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
output = ""
for word in words:
if letter in word:
output += word + " "
print(output.rstrip()) # Print without trailing whitespace
或者(我不太建议这样做,因为这样会让意图不太明显)你可以检查是否是最后一个单词,然后打印一个换行符,而不是额外的空格(这样你就不需要额外的 print()
了)。
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
for index in range(len(words)):
if letter in words[index]:
the_end = "\n" if index == len(words) - 1 else " " # Newline only if it is the last word
print(word, end=the_end)
0
你差不多就要成功了。在你的 for
循环里,现在只需要加一个条件判断。
条件判断就是用来判断某个事情是 真
还是 假
的语句。
你可能想要的是:
for e in d:
if a in e:
print(e)
0
为什么不直接这样做呢:
a = input("Letter: ")
b = input("Input: ")
words = b.split()
for word in words:
if a in word:
print(word)