str.find
The idea you used is very close to the final solution, the main problem is that the find
method returns only the index of the first occurrence of the searched letter.
str.find (sub [ start [ end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]
. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
To find all occurrences, we could use the start
parameter, which defines where to begin parsing within string . If we set this value to be the first position of the letter, the method returns the position of the second occurrence.
nome = input("Digite o nome: ")
start = 0
while True:
index = nome.find("a", start)
if index == -1:
break
print("Letra 'a' encontrada na posição %d" % index)
start = index+1
For an entry equal to batata
, the output would be:
Letra 'a' encontrada na posição 1
Letra 'a' encontrada na posição 3
Letra 'a' encontrada na posição 5
For positions 1, 3 and 5 there is the letter "a".
If we want to do the same process for the other vowels, we would have to repeat the code. Also, this way differentiates the letters "a" and "A", so for the Anderson name, the letter "a" would not be found.
loop
Another fairly simple, easy-to-understand method for beginners is to iterate through a loop and check if the letter is a vowel. For example:
nome = input("Digite o nome: ")
for index, letra in enumerate(nome):
if letra == 'a' or \
letra == 'e' or \
letra == 'i' or \
letra == 'u':
print("Encontrado a letra '%c' na posição %d" % (letra, index))
For the name batata
the output will be:
Encontrado a letra 'a' na posição 1
Encontrado a letra 'a' na posição 3
Encontrado a letra 'a' na posição 5
This method can still be optimized for:
nome = input("Digite o nome: ")
for index, letra in enumerate(nome):
if letra in "aeiou":
print("Encontrado a letra '%c' na posição %d" % (letra, index))
In this way it would be easier to get around the problem of lowercase or uppercase letters, as it would be enough to do:
nome = input("Digite o nome: ")
for index, letra in enumerate(nome):
if letra in "aeiouAEIOU":
print("Encontrado a letra '%c' na posição %d" % (letra, index))
That the program would work for any vowel, both lower case and upper case.
re.findall
A somewhat more advanced solution is using regular expressions. Python has a native library called re
for this, having a function called findall
, which returns the list of all occurrences of a pattern in a string . For example, the following code:
import re
nome = input("Digite o nome: ")
print(re.findall(r"[aeiou]", nome, re.IGNORECASE))
Returns the list of all the vowels found in the name. For batata
, would be returned ['a', 'a', 'a']
, referring to the three "a" in the word.