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.
s = 'ABCDEFGHIJKLMNOP'
targets = 'CDE','XYZ','JKL'
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')
for t in targets:
i = s.find(t)
if i != -1:
print(s[i:])
else:
print(t,'does not exist')
CDEFGHIJKLMNOP
XYZ does not exist
JKLMNOP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With