Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I'm new to Python and coding and stuck at comparing a substring to another string.

I've got: string sq and pattern STR.

Goal: I'm trying to count the max number of STR patterns appearing in that string in a row.

This is part of the code:

 STR = key

        counter = 0

        maximum = 0

        for i in sq:

            while sq[i:i+len(STR)] == STR:

                counter += 1

                i += len(STR)

The problem seems to appear in the "while part", saying TypeError: can only concatenate str (not "int") to str.

I see it treats i as a character and len(STR) as an int, but I don't get how to fix this. The idea is to take the first substring equal to the length of STR and figure out whether this substring and STR pattern are identical.

1 Answer

0 votes
by (36.8k points)

By looping using:

for i in sq:

you are looping over the elements of sq.

If instead, you want the variable i to loop over the possible indexes of sq, you would generally loop over the range(len(sq)), so that you get values from 0 to len(sq) - 1.

for i in range(len(sq)):

However, in this case, you are wanting to assign to i inside the loop:

i += len(STR)

This will not have the desired effect if you are looping over the range(...) because on the next iteration it will be assigned to the next value from range, ignoring the increment that was added. In general, one should not assign a loop variable inside the loop.

So it would probably most easily be implemented with a while loop, and you set the desired value of i explicitly (i=0 to initialise, i+=1 before restarting the loop), and then you can have whatever other assignments you want inside the loop.

STR = "ell"

sq = "well, well, hello world"

counter = 0

i = 0

while i < len(sq):

    if sq[i:i+len(STR)] == STR:

        counter += 1

        i += len(STR)

    i += 1

print(counter) # prints 3

(You could perhaps save len(sq) and len(STR) in other variables to save evaluating them repeatedly.)

If you are a beginner and want to know more about Data Science the do check out the Data Science course

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...