I couldn’t understand what you meant by "when I add the .lower()
she changes to str
and the code no longer works", but anyway, if you want to capitalize everything (or everything in capital letters) in order to be able to make comparisons, one option would be to make input
:
# transforma tudo em maiúscula
frase = input('Digite uma frase: ').upper()
letra = input('Qual letra você deseja escanear? ').upper()
# ou transforma tudo em minúscula
frase = input('Digite uma frase: ').lower()
letra = input('Qual letra você deseja escanear? ').lower()
Another detail is that you don’t have to do two loops. The enumerate
already returns at the same time the position and the respective character, so just do:
c = 0
pos = []
for posicao, caractere in enumerate(frase):
if letra == caractere:
pos.append(posicao)
c += 1
Or you can store only the list of positions, without needing the counter. If at the end of the for
the list is empty, it is because it did not find anything:
pos = []
for posicao, caractere in enumerate(frase):
if letra == caractere:
pos.append(posicao)
if pos:
print(f'Existem {len(pos)} letra(s) "{letra}" na frase, nas posições {pos}.')
else:
print(f'Não existe nenhum "{letra}" nesta frase.')
The if pos:
check if the list is not empty (here is used the fact that empty lists are considered False
). Then, to know how many times the letter occurs, just get the list size with len
.
You can still change the for
above by a comprehensilist on, much more succinct and pythonic.:
pos = [ posicao for posicao, caractere in enumerate(frase) if letra == caractere ]
Of course you could also leave the sentence intact and only convert it to uppercase (or lowercase) when comparing the characters:
frase = input('Digite uma frase: ')
letra = input('Qual letra você deseja escanear? ').lower()
pos = [ posicao for posicao, caractere in enumerate(frase) if letra == caractere.lower() ]
Finally, if you really want to make a comparison case insensitive, can use the method casefold
. It is similar to lower()
, but a little more "aggressive" and treats special cases, as for example the character ß
, which, when converted to capital, becomes "SS" (then 'ß'.upper().lower()
returns "ss"):
print('ß'.lower() == 'SS'.lower()) # False
print('ß'.casefold() == 'SS'.casefold()) # True
Of course, for texts in Portuguese, it won’t make that much difference to use lower()
or casefold()
, but anyway, the tip is recorded.
That’s what you’re trying to do?
frase = input('Digite uma frase: ').upper()
andletra = input('Qual letra você deseja escanear? ').upper()
– Augusto Vasques