Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding substring in python [duplicate]

I'm new to python and I'm trying different methods to accomplish the same task, right now I'm trying to figure out how to get a substring out of a string using a for loop and a while loop. I quickly found that this is a really easy task to accomplish using regex. For example if I have a string: "ABCDEFGHIJKLMNOP" and I want to find if "CDE" exists then print out "CDE" + the rest of the string how would I do that using loops? Right now I'm using:

for i, c in enumerate(myString):

which returns each index and character, which I feel is a start but I can't figure out what to do after. I also know there are a lot of build in functions to find substrings by doing: myString.(Function) but I would still like to know if it's possible doing this with loops.

like image 811
Ryan Sayles Avatar asked Jan 13 '23 08:01

Ryan Sayles


1 Answers

Given:

s = 'ABCDEFGHIJKLMNOP'
targets = 'CDE','XYZ','JKL'

With loops:

for t in targets:
    for i in range(len(s) - len(t) + 1):
        for j in range(len(t)):
            if s[i + j] != t[j]:
                break
        else:
            print(s[i:])
            break
    else:
        print(t,'does not exist')

Pythonic way:

for t in targets:
    i = s.find(t)
    if i != -1:
        print(s[i:])
    else:
        print(t,'does not exist')

Output (in both cases):

CDEFGHIJKLMNOP
XYZ does not exist
JKLMNOP
like image 138
Mark Tolonen Avatar answered Jan 16 '23 19:01

Mark Tolonen