0

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.

Muna N
  • 1
  • The answer of @mark is the simplest on, alternatively you can use the package "re", to find all occurrences via a regex expression: len(re.findall("a", "banana")) – Dieter Apr 17 '22 at 20:55

1 Answers1

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