Search code examples
pythonsubstringconcatenationindices

Identifying a substring in Python (moving along indices within a string) - can only concatenate str (not "int") to str


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 pattern 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.

Thank you!


Solution

  • 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 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 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 to 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):
        while sq[i:i+len(STR)] == STR:  # re use of while here, see comments
            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.)