-1

I have a strings like this:

string1 = "foo_bar_of_foo"
string2 = "foo_bar"

This answer tells me how to check for an instance of "foo" in a string, but what if I want to check for exactly n instances of "foo" in a string?

for example:

#pseudo-code = find(2 instances of foo)

if "foo" in string1: 
    print("true") #this should print

if "foo" in string2:
    print("false") #this shouldn't print since string2 only has 1 instance of foo

I can think of long and complicated ways of doing this, but I was wondering what the pythonic approach would be?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80

1 Answers1

1

Just use str.count:

string1 = "foo_bar_of_foo"
string2 = "foo_bar"

if string1.count('foo') == 2: 
    print("true")

if string2.count('foo') == 2:
    print("false")
iz_
  • 15,923
  • 3
  • 25
  • 40