How do you find a string in another string in python? for example, finding the string "a" in the string "banana" and print how many times it occurs.
Asked
Active
Viewed 29 times
1 Answers
0
I suggest you check out this answer: https://stackoverflow.com/a/4664889/7509907
Basically what you can do is to use regular expressions like this:
import re
string = 'banana'
substring = 'a'
# this will give you a list of indexes where the substring occurs in the string
# you can use len() to get the number of occurances
occurance_idxs = [m.start() for m in re.finditer(substring, string)]
print(occurance_idxs)
print(len(occurance_idxs))
output
[1, 3, 5]
3

D.Manasreh
- 900
- 1
- 5
- 9