我正在嘗試檢查用戶輸入是否包含元音。但是,我只發現了如何一次檢查一個元音,但不是全部。
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?
uj5u.com熱心網友回復:
如果您不需要知道存在哪些元音,您可以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.")
uj5u.com熱心網友回復:
跟蹤的一種方法是創建一個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
uj5u.com熱心網友回復:
正則運算式不僅可以告訴您字串中是否有元音,還可以告訴您哪些元音及其順序。
>>> import re
>>> re.findall('[aeiou]', 'hello')
['e', 'o']
uj5u.com熱心網友回復:
我可以解決你的問題。這是代碼:
vowels = {'a','e','i','o','u'}
word = input("Enter a word: ")
for vowel in word:
if vowel in vowels:
print(vowel,"is vowel")
uj5u.com熱心網友回復:
您必須遍歷串列。
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427564.html
