我需要编写一个函数来计算用户输入的字符串中的字符和元音,并编写一个调用该函数的例程并显示:
$ ./count_all.py
Enter some words: The sun rises in the East and sets in the West
13 letters in 47 are vowels.
最好的方法是什么?
答案 0 :(得分:1)
不可读的1个班轮:
import re
stringToTest = "a9821e89asdi89123o9812378u"
print(str(len(re.findall(r"a|e|i|o|u", stringToTest, re.IGNORECASE))) + " letters in " + str(len(stringToTest)) + " are vowels")
#6 letters in 26 are vowels
可读表格
import re
stringToTest = "a9821e89asdi89123o9812378u"
stringLength = len(stringToTest) #length of stirng, this is how many characters we have
regexResult = re.findall(r"a|e|i|o|u", stringToTest, re.IGNORECASE) #match for a or e or i or o or u
numberVowels = len(regexResult) #our number of vowels is how many regex matches we got
print(str(numberVowels) + " vowels in " + str(stringLength) + " characters")
#6 vowels in 26 characters