简体   繁体   English

您如何检查字符串是否包含列表中的内容并打印出来?

[英]How do you check if a string has something from the list and print it?

I'm trying to make a program that takes one word from the user and checks from a list of vowels and prints the vowels that are found in that word and how many were found.我正在尝试制作一个程序,从用户那里获取一个单词并从元音列表中检查并打印在该单词中找到的元音以及找到的元音数量。 This is what I have so far, it's super incorrect but I tried something.这是我到目前为止所拥有的,它非常不正确,但我尝试了一些东西。

print("This program will count the total number of vowels in the word you enter.")

vowels = ["a", "e", "i", "o", "u"]
userWord = input("Please enter a single word: ")
if vowels in userWord:
    print(vowels)
    vowelCount = 0
    
    vowelCount = vowelCount + 1
    
    print("There are " + vowelCount + " total vowels in " + userWord)

Use the sum() function to count the number of vowels in the word.使用sum() function 来计算单词中元音的数量。 The generator expression produces True for each vowel that is found at least once, and True counts as 1 to sum() .生成器表达式为至少找到一次的每个元音生成True ,并且True计为1sum()

vowelCount = sum(vowel in userWord for vowel in vowels)
print(f"There are {vowelCount} total vowels in {userWord}")

Something you can do if you are starting out with Python is to iterate over every letter in the input word.如果您从 Python 开始,您可以做的是遍历输入单词中的每个字母。

In each iteration you then check if the letter is in the vowel list like so:然后在每次迭代中检查字母是否在元音列表中,如下所示:

print("This program will count the total number of vowels in the word you enter.")

vowels = ["a", "e", "i", "o", "u"]
userWord = input("Please enter a single word: ")
vowelCount = 0
foundVowels = []

for letter in userWord:
    if letter in vowels:
        foundVowels.append(letter)
        vowelCount += 1
print("There are " + str(vowelCount) + " total vowels in " + userWord + ": " + str(foundVowels))
vowels=['a','e','i','o','u']
count=0
ls=[]
wordfromUser=input("Enter a word: ")
for i in wordfromUser:
  if i in vowels:
    count+=1
    ls.append(i)
print("There are " + str(count) + " total vowels in " + wordfromUser)

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

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