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      
frooty
  • 69
  • 1
  • 1
  • 7

2 Answers2

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
Dave
  • 1,784
  • 2
  • 23
  • 35
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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321