Search for substring in python

I am new to python and I am trying to use different methods to accomplish the same task. Now I am trying to figure out how to get a substring from a string using for loopand while loop, I quickly found that it is a very simple task to accomplish regex. For example, if I have a line: "ABCDEFGHIJKLMNOP" and I want to find out if "CDE" exists and then print "CDE" + the rest of the line, how can I do this with loops? Now I am using:

for i, c in enumerate(myString):

which returns every index and character, which I believe is the beginning, but I cannot figure out what to do after. I also know that there are many built-in functions for finding substrings by executing: myString. (Function), but I still would like to know if it is possible to do this using loops.

+4
source share
3 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')

The 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
+5
source

Here is a quick way to do this:

s = "ABCDEFGHIJKLMNOP"
if "CDE" in s: 
    print s[s.find("CDE")+len("CDE"):]
else: 
    print s

Print

FGHIJKLMNOP

A caveat here, of course, if the substring is not found, the original string will be returned.

? , . , (: - , , ):

def remainder(string, substring):
    if substring in string:
        return string[string.find(substring)+len(substring):]
    else:
        return string
+3

Getting the rest of the string using a for loop:

n = len(substr)
rest = next((s[i+n:] for i in range(len(s) - n + 1) if s[i:i+n] == substr),
            None) # return None if substr not in s

This is equivalent to:

_, sep, rest = s.partition(substr)
if substr and not sep: # substr not in s
   rest = None
0
source

All Articles