Contagem
Vamos considerar alguns outros métodos que podem ser aplicados a strings. Um deles pode nos ajudar a contar o número de aparições de algum símbolo/substring dentro de uma string.
Para contar o número de símbolos/substrings em uma string, utilize o método .count(símbolo/substring)
. Por exemplo,
9
1
2
3
string = "String Manipulation in Python"
print("letter i appeared", string.count('i'), "times in the string.")
print("letter t appeared", string.count('t'), "times in the string.")
123string = "String Manipulation in Python" print("letter i appeared", string.count('i'), "times in the string.") print("letter t appeared", string.count('t'), "times in the string.")
Nota
Este método diferencia maiúsculas de minúsculas. Para o exemplo acima,
string.count('m')
retornará 0, enquantostring.count('M')
retornará 1.
Tarefa
Swipe to start coding
Você recebeu a string
"Introduction to Python". Você precisa calcular o número de símbolos 'o'
e 't'
nesta string.
Solução
9
1
2
3
4
5
6
7
# Variable
string = "Introduction to Python"
# Calculate number of letter 'o'
print(string.count('o'))
# Calculate number of letter 't'
print(string.count('t'))
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 2. Capítulo 1
9
1
2
3
4
5
6
7
# Variable
string = "Introduction to Python"
# Calculate number of letter 'o'
print(string.___(___))
# Calculate number of letter 't'
print(___)
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo