0

What would be the textbook way of accomplishing the following tasks:

I have a string s of the from s_s * s_l * s_q * s_r * s_e, where by * I mean the concatenation operator.

Given s, s_l and s_r I am interested in returning s_q, we may assume that s_l and s_r only occur once in s.

As an example: s = "abcdefghij", s_l = "cd", s_r = "hi" so s_q = "efg".

Would a regex approach be appropriate in this situation?

2 Answers 2

1
In [110]: s[s.find(s_l)+len(s_l): s.find(s_r)]
Out[110]: 'efg'
Sign up to request clarification or add additional context in comments.

2 Comments

You might want to use rfind on s_r to take the first occurrence from the right
@bnjmn the OP assumes s_r occurs only once in s ;)
0

You could split the string, since you know that s_l and s_r only occur once each:

s = "abcdefghij"
s_l = "cd"
s_r = "hi"

print s.split(s_l)[1].split(s_r)[0] # Returns efg

You don't need to use regular expressions, because s_l and s_r are static. If you didn't know what s_l and s_r are going to be in advance, only that they match some pattern, then regular expressions might be helpful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.