How to count occurrences of a substring in a string in Python?

3

How do I read two strings and check the number of occurrences of the second string in the first?

Example: If the first string entered is "abracadabra" and the second "bra" , then the number of occurrences will be 2 .

    
asked by anonymous 17.04.2017 / 04:33

2 answers

5

Use str.count:

 >>> nStr = 'abracadabra'
 >>> nStr.count('bra')

Source - Determining how many times a substring occurs in a string in Python

Python, Tutorials

    
17.04.2017 / 04:52
0
frase = str(input("Digite a frase a se analisada: "))
palavra = str(input("Ocorrências da palavra/letra: "))

resultado = frase.count(palavra)

print(f"Na frase |{frase}|, a palavra/letra |{palavra}| apareceu {resultado} vezes")
    
12.04.2018 / 18:17