1

我正在尝试检查用户输入是否包含元音。但是,我只发现了如何一次检查一个元音,但不是全部。

vowel = ("a")

word = input("type a word: ")

if vowel in word:
 print (f"There is the vowel {vowel} in your word")
else:
 print ("There is no vowel in your word")

这似乎可行,但是如果我尝试将元音变量放入列表中,则会出现错误。["a","e","i","o","u"]

任何想法如何同时检查 eiou?

4

5 回答 5

2

如果您不需要知道存在哪些元音,您可以any按如下方式使用。

vowels = ("a", "e", "i", "o", "u")

word = input("type a word: ")

if any(v in word for v in vowels):
    print("There is at least one vowel in your word.")
else:
    print("There is no vowel in your word.")
于 2022-02-13T17:46:06.420 回答
1

跟踪的一种方法是创建一个existence列表来保存单词中存在的所有元音。

existence = []
vowels = ["a","e","i","o","u"]
test_word = "hello" # You can change this to receive input from user

for char in  test_word:
    if char in vowels:
        existence.append(char)
if existence and len(existence) > 0:
    for char in existence:
        print(f"These vowels exist in your input {test_word} - {char}")
else:
     print(f"There are no vowels existing in your input {test_word}")

输出:

These vowels exist in your input hello - e
These vowels exist in your input hello - o
于 2022-02-13T17:49:36.723 回答
1

正则表达式不仅可以告诉您字符串中是否有元音,还可以告诉您哪些元音及其顺序。

>>> import re
>>> re.findall('[aeiou]', 'hello')
['e', 'o']
于 2022-02-13T17:50:57.837 回答
0

我可以解决你的问题。这是代码:

vowels = {'a','e','i','o','u'}

word = input("Enter a word: ")

for vowel in word:

  if vowel in vowels:
    print(vowel,"is vowel")
于 2022-02-14T13:43:14.073 回答
-1

您必须遍历列表。

vowels =  ["a","e","i","o","u"]

word = input("type a word: ")

for vowel in vowels:
  if vowel in word:
     print (f"There is the vowel {vowel} in your word")
  else:
     print ("There is no vowel in your word")

迭代是您遍历列表中每个项目的过程。

例如。

list_a = ['a', 'b', 'c' ]

for item in list_a:
  print(item)

#output will be a b c 

因为其他用户在评论中抱怨。如果你想在找到元音后停止循环,你应该添加 break 语句

vowels =  ["a","e","i","o","u"]

word = input("type a word: ")

for vowel in vowels:
  if vowel in word:
     print (f"There is the vowel {vowel} in your word")
     break
  else:
     print ("There is no vowel in your word")
于 2022-02-13T17:31:00.313 回答