4

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.

Ryan Sayles
  • 3,389
  • 11
  • 56
  • 79

3 Answers3

6

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
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
3

Here's a concise way to do so:

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

Prints:

FGHIJKLMNOP

The caveat here is of course, if the sub-string is not found, the original string will be returned.

Why do this? Doing so allows you to check whether or not the original string was found or not. As such, this can be conceptualized into a simple function (warning: no type checks enforced for brevity - it is left up to the reader to implement them as necessary):

def remainder(string, substring):
    if substring in string:
        return string[string.find(substring)+len(substring):]
    else:
        return string
jrd1
  • 10,358
  • 4
  • 34
  • 51
0

Getting the remainder 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

It is equivalent to:

_, sep, rest = s.partition(substr)
if substr and not sep: # substr not in s
   rest = None
jfs
  • 399,953
  • 195
  • 994
  • 1,670