You can do it like this:
1.
def conta_vogais(string):
string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
result = {}
vogais = 'aeiou'
for i in vogais:
if i in string:
result[i] = string.count(i)
return result
print(conta_vogais('olaaa'))
Or by making dictinary compreension suffice::
def conta_vogais(string):
string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
vogais = 'aeiou'
return {i: string.count(i) for i in vogais if i in string}
print(conta_vogais('olaaa'))
Output:
{'a': 3, 'o': 1}
2.
I did the above example in order to count and return the number of times it appears, and only if it appears. But if you simply want total vowels you can:
def conta_vogais(string):
string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
result = 0
vogais = 'aeiou'
for i in vogais:
result += string.count(i)
return result
print(conta_vogais('olaaa'))
OR:
def conta_vogais(string):
string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
vogais = 'aeiou'
return sum(string.count(i) for i in vogais)
print(conta_vogais('olaaa'))
What will happen in this case 4
3.
By the way, to complete a little more the answer, you can also return the number of times that appears each (those that do not appear including):
def conta_vogais(string):
string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
result = {}
vogais = 'aeiou'
for i in vogais:
result[i] = string.count(i)
return result
print(conta_vogais('olaaa'))
Or by making dictinary compreension suffice:
def conta_vogais(string):
string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
vogais = 'aeiou'
return {i: string.count(i) for i in vogais}
print(conta_vogais('olaaa'))
Output:
{'a': 3, 'e': 0, 'u': 0, 'i': 0, 'o': 1}
@Miguel O
Counter
accepts an iterable-or-Mapping and a string in Python is iterable. Typefor c in 'teste': print(c)
.– Michelle Akemi
No problem, @Miguel. This shows how often a "insightful" code, as I said, is not so good to be maintained. It gets messy all in one line and it’s not clear what’s going on.
– Michelle Akemi
@Miguel but there you would know the total of all vowels, not the amount of each. On the second comment, I totally agree. I edited the code.
– Michelle Akemi