One of the ways to resolve this issue is by using List Comprehensions.
For this you can use the following logic:
- Define a variable in which the captured string will be stored;
- Define a variable in which the captured character to count will be stored;
- Implement a comrehension list;
- Display the result.
With this logic you can implement the following code:
frase = input('Digite uma frase: ')
caract = input('Digite o carácter a ser contado: ')
cont = sum([1 for i in frase if i == caract])
print(f'Na frase existe {cont} caracteres "{caract}".')
How this code works?
Initially this code captures a string - string - and, also, a character we want to count. Later, a list will be mounted by list comprehension. This list will be mounted with only values 1 if, and only if, the temporary variable "i = caract". Then the function sum() shall sum up the amount of 1 existing grandlist. Finally the amount of character analyzed will be displayed.
Testing the code:
Imagine that when we executed this code we typed the following sentence:
diclorodifeniltricloroetano foi o um dos primeiros pesticidas modernos
and then specify the character "the" to be counted.
The exit code will be:
Na frase existe 11 caracteres "o".
Hello Matthew, Welcome to Stackoverflow PT! Try to explain your question better with some code you already have, and detail a little more. You want the highest occurrence character in a string or want all?
– Um Programador