0

str1 is a string in which the search is to be performed (the haystack). str2 is the string to be found (the needle). count will count the number of occurences of str2 in str1.

The code below gives me a syntax error in the last line. Please suggest changes.

str1 = raw_input()
str2 = raw_input()
count = 0
for i in range(0,len(str1)) :

    if ( str1.find(str2, i, i+len(str2))) : 
        count=count+1
print count      
6
  • 1
    Use str1.count(str2)..
    – Maroun
    Jan 22, 2015 at 12:38
  • 2
    print is a function in Python 3.
    – interjay
    Jan 22, 2015 at 12:38
  • @MarounMaroun, that won't count overlapping strings Jan 22, 2015 at 12:39
  • @MarounMaroun, edited too! Jan 22, 2015 at 12:39
  • @PadraicCunningham I don't get it.. what do you mean by overlapping strings?
    – Maroun
    Jan 22, 2015 at 12:42

2 Answers 2

4

To find out if a string is a substring of another string, you can use the in operator

"abc" in "abcd" # will return true

And to count occurences you can use the count method of string

"abcda".count("a") # will return 2
0
3

If you want to count how many times str2 is in str1 including overlapping strings:

str1 = raw_input() # input() if using python3
str2 = raw_input() 
print(sum(str1[i:i+len(str2)] == str2 for i in xrange(len(str1)) ))

Example:

In [12]: paste
str1 = raw_input()
str2 = raw_input()
sum(str1[i:i+len(str2)] == str2 for i in xrange(len(str1)))

## -- End pasted text --
bobob
bob
Out[12]: 2
2
  • good answer, this covers overlapping strings too.
    – Maroun
    Jan 22, 2015 at 12:44
  • 1
    @MarounMaroun, i may be wrong but the OP's code does look like some attempt at doing the same. Jan 22, 2015 at 12:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.