Number of vowels in the Python function

Asked

Viewed 2,571 times

0

I want to do a function in Python that makes a count of how many vowels there are in a string in which the user type.

My code:

def cacavogais():
    i = 0
    j = 0
    string = str (input("Digite alguma coisa: "))
    for i in string:
        if i.lower() in string:
             j+=1
    print ("A string digitada foi: {}".format(string))
    print ("A quantidade de vogais que possui é {}".format(j))

cacavogais()
  • 1

    And what’s the mistake Alex? Apparently there doesn’t seem to be anything wrong. You’re just not printing j, but seems to be counting normally.

  • Jeez fuck, I’m forehead here.

  • 2

    Alex, string[i] doesn’t make sense, because i will be every letter of the string. So it’s easier to simply use the operator in. Kind of: if i.lower() in "aeiou":

  • It worked very well no, apparently does not present the expected number of vowels, I will edit my code.

  • 1

    I will create an answer with the explanation. Only ready-made code will not help you understand the concept.

  • It will not be necessary already posted the reply you wanted and now I understood what was wrong, thanks anyway.

  • Fernando, excellent, post as it may help another person who by venture goes through the same problem. :)

  • Okay, if you already know what the str.lower() and already knows the operator in all right...

  • 1

    All right, Filipe.. I’ll post it the same way then...

  • Tá @fernandosavio.

  • Posted... Any questions just comment on the reply...

Show 6 more comments

4 answers

4

One way to solve it is to use a comprehensilist on (much more succinct and pythonic):

vogais = 'aeiou'
s = 'abcdefghijABCEx'
qtd_vogais = len([c for c in s.lower() if c in vogais])
print(qtd_vogais) # 5

The line qtd_vogais = len([c for c in s.lower() if c in vogais]) is equivalent to loop suggested by the other answers:

vogais = 'aeiou'
s = 'abcdefghijABCEx'
qtd_vogais = 0
for c in s.lower():
    if c in vogais:
        qtd_vogais += 1

print(qtd_vogais) # 5

Basically, s.lower() turns the string into lower-case letters, and for c in s.lower() makes a loop for all characters in the string. At each iteration, c will be a character. Then just test if c is a vowel and increment the counter.

In the case of comprehensilist on, a list with all vowels (because the expression is inside brackets), and the function len returns the size of this list.


If you also want to consider accented characters, you can use the module unicodedata:

from unicodedata import normalize

vogais = 'aeiou'
s = 'ábcdefghijABCEx'
qtd_vogais = len([c for c in normalize('NFD', s.lower()) if c in vogais])
print(qtd_vogais) # 5

In a nutshell, the normalization in NFD "breaks" the "á" in two characters: the a (without accent) and the accent itself. Thus, it is possible to check the vowels in the same way as before. (has a more detailed explanation of the standardisation here, here and here - although not in Python, the idea is the same)


Another option is to use a Counter:

from collections import Counter
from unicodedata import normalize

vogais = 'aeiou'
s = 'ábcdefghijABCEx'
c = Counter(normalize('NFD', s.lower()))
qtd_vogais = sum(qtd for letra, qtd in c.items() if letra in vogais)
print(qtd_vogais) # 5

The Counter resulting is a dictionary, whose keys are string characters and values are the amount of times each character occurs in the string.

Then just go through it, see which keys are vowels and add up the amounts.

  • 1

    +1 by Unicode normalization... is always good. :)

2


You can do it like this:

def cacavogais():
    i = 0
    j = 0
    string = str (input("Digite alguma coisa: "))
    for i in string:
        if (i == 'A' or i == 'a'
        or i == 'E' or i == 'e'
        or i == 'I' or i == 'i'
        or i == 'O' or i == 'o'
        or i == 'U' or i == 'u'):
             j+=1
    print("vogais: ", j)

cacavogais()

But he’s got better ways of doing it here. Another way to do this would be like this, for example:

def cacavogais():
    i = 0
    j = 0
    string = str (input("Digite alguma coisa: "))
    string = string.lower()
    for i in string:
        if (i == 'a'
        or i == 'e'
        or i == 'i'
        or i == 'o'
        or i == 'u'):
             j+=1
    print("vogais: ", j)

cacavogais()

2

To count vowels we will follow the following steps:

  1. Read a user-typed string
  2. Read letter by string typed by user
  3. Check if this letter is a vowel (for educational purposes we will ignore accents)
  4. If it’s a vowel, we increment a counter
  5. After reading the whole word, we will show the contents of the counter

Step by step

  1. Read a user-typed string

    We will use the method str.input() to receive the user string

    palavra = input("Digite uma palavra: ")
    
  2. Read letter by string typed by user

    We will use the for to iterate over each letter of the word typed.

    for letra in palavra:
        # ...
    
  3. Check if this letter is a vowel (for educational purposes we will ignore accents)

    We’ll use a if to test whether the letter is a vowel or not.

    For this we will test if the letter exists inside the string "aeiouAEIOU", if it exists is a vowel (uppercase or lowercase).

    for letra in palavra:
        if letra in "aeiouAEIOU":
            # ...
    
  4. If it’s a vowel, we increment a counter

    contador = 0
    for letra in palavra:
        if letra in "aeiouAEIOU":
            contador += 1
    
  5. After reading the whole word, we will show the contents of the counter

    print("A palavra '{}' tem {} vogais.".format(palavra, contador))
    

The final code will remain:

palavra = input("Digite uma palavra: ")
contador = 0

for letra in palavra:
    if letra in "aeiouAEIOU":
        contador += 1

print("A palavra '{}' tem {} vogais.".format(palavra, contador))

Repl.it with the code running


Extra

You can use the function len() and list-comprehensions to do the same thing, but with the leanest code:

palavra = input("Digite uma palavra: ")
contador = len([letra for letra in palavra if letra in "aeiouAEIOU"])
print("A palavra '{}' tem {} vogais.".format(palavra, contador))

1

Alex, follow the example below that solves your problem.

def contarVogais(a):
    vogais = "aeuioAEUIO"
    result = 0
    for char in a:
        if char in vogais:
            result = result + 1
    return result

contarVogais("ajdgejfifhou")

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.