user_input_1 = str(input("Enter fruit name"))
variable_count_vowel = 0
vowels = set("AEIOUaeiou")
for x in user_input_1:
if x in vowels:
variable_count_vowel = variable_count_vowel 1
print("Number of vowels within fruit name",user_input_1,"=",variable_count_vowel)
我一直在做一個任務,程式計算用戶輸入中找到的特定元音的數量,我想把這個for
回圈變成一個函式。
uj5u.com熱心網友回復:
我建議在函式內或不在函式內使用正則運算式:
import re
user_input_1 = str(input("Enter fruit name"))
print(len(re.findall(r'[AEIOUaeiou]',user_input1)))
uj5u.com熱心網友回復:
有很多方法可以做到這一點。一種方法是將sum()與這樣的生成器結合使用:
VOWELS = set('aeiouAEIOU')
def vowel_count(s):
return sum(1 for c in s if c in VOWELS)
print(vowel_count('abc'))
uj5u.com熱心網友回復:
正如mkrieger1 所建議的,您可以只在 for 回圈上定義函式,然后縮進它:
def vowel_count(text, vowels="AEIOUaeiou"):
variable_count_vowel = 0
for x in text:
if x in vowels:
variable_count_vowel = 1
return variable_count_vowel
user_input_1 = str(input("Enter fruit name"))
print("Number of vowels within fruit name",user_input_1,"=",vowel_count(user_input_1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470321.html