计算字符串

时间:2016-03-21 16:12:20

标签: python python-2.7 python-3.x

vowels = 'aeiou'
ip_str = input("Enter a string: ")
ip_str = ip_str.casefold()
count = {}.fromkeys('aeiouAEIOU',0)
for char in ip_str:
   if char in count:
       count[char] += 1

print(count)

如何在Python中编写程序来接受字符串并计算其中元音的数量?

2 个答案:

答案 0 :(得分:2)

您可以使用sum()功能:

vowels = "aeiou"
number = sum(1 for char in ip_str if char.lower() in vowels)

如果您想根据字典查找计数,请执行以下操作:

number = sum(count.values())

答案 1 :(得分:0)

您已经计算过每个元音的代码。如果您想知道元音的总数,那么只需按照以下步骤保持总计:

ip_str = input("Enter a string: ")
ip_str = ip_str.casefold()
count = {}.fromkeys('aeiou',0)
total = 0

for char in ip_str:
   if char in count:
       count[char] += 1
       total += 1

print(count)
print("Number of vowels:", total)

例如:

Enter a string: Hello THERE
{'a': 0, 'o': 1, 'u': 0, 'i': 0, 'e': 3}
Number of vowels: 4

如果您希望它分别计算大写和小写:

ip_str = input("Enter a string: ")
count = {}.fromkeys('aeiouAEIOU', 0)
total = 0

for char in ip_str:
   if char in count:
       count[char] += 1
       total += 1

print(count)
print("Number of vowels:", total)

给你:

Enter a string: Hello THERE
{'i': 0, 'O': 0, 'e': 1, 'U': 0, 'o': 1, 'E': 2, 'a': 0, 'I': 0, 'A': 0, 'u': 0}
Number of vowels: 4