Quick and dirty example based on your second example:
text = 'I want to find a string between two substrings'
start = 'find a '
end = 'substrings'
s_idx = text.index(start) + len(start) if start in text else -1
e_idx = text.index(end) if end in text else -1
if s_idx > -1 and e_idx > -1:
print(text[s_idx:e_idx])
You have to check if substring is a part of a string or else str.index() throws a ValueError.
EDIT: Output based on first example:
start_list = ["work", "start", "also"]
end_list = ["of", "end", "substrings"]
text = "This can also work on a list of start and end substrings"
print("* Example with a list of start and end strings, stops on a first match")
print("- Text: {0}".format(text))
print("- Start: {0}".format(start_list))
print("- End: {0}".format(end_list))
s_idx = -1
for string in start_list:
if string in text:
s_idx = text.index(string) + len(string)
# we're breaking on a first find.
break
e_idx = -1
for string in end_list:
if string in text:
e_idx = text.index(string)
# we're breaking on a first find.
break
if e_idx > -1 and s_idx > -1:
print(text[s_idx:e_idx])
Or, if you even want to go further and find all substrings between all occurrences:
print("* Example with a list of start and end strings, finds all matches")
print("- Text: {0}".format(text))
print("- Start: {0}".format(start_list))
print("- End: {0}".format(end_list))
s_idxs = []
e_idxs = []
for string in start_list:
if string in text:
s_idxs.append(text.index(string) + len(string))
for string in end_list:
if string in text:
e_idxs.append(text.index(string))
for s_idx in s_idxs:
for e_idx in e_idxs:
if e_idx <= s_idx:
print("ignoring end index {0}, it's before our start at {1}!".format(e_idx, s_idx))
# end index is lower than start index, ignoring it.
continue
print("{0}:{1} => {2}".format(s_idx, e_idx, text[s_idx:e_idx]))
You can further 'shorten' and improve this code, this is just a quick and dirty write up.
startlist isn't producing error?text[text.index(start)+len(start):text.index(end)]should output "string". Are you expecting a different output? Also, how does that example relate to the list of input and output posted above it?startandendare lists as described in first example.