3

I need help with extracting multiple substrings from a string and assign it to a list, and those required substrings have similar start substring and end substring,

for example if I have a string like this: "start something something end start nothing nothing end"

how do I extract "something something" and "nothing nothing" and append it to a list.

3
  • 1
    Extract them based on what? If you know "something something" can't you just create a string containing "something something"? Commented Nov 2, 2019 at 16:23
  • Welcome to Stack Overflow. Please take the tour and then read How to Ask. Commented Nov 2, 2019 at 16:26
  • Not sure exactly what you are looking for but have a look at the re module. It should be able to get you where you want if you are looking at extracting words based on context. Commented Nov 2, 2019 at 16:27

1 Answer 1

4

You can use re.findall.


>>> text = 'start something something end start nothing nothing end'
>>> re.findall('start (.+?) end', text)
['something something', 'nothing nothing']

Return all non-overlapping matches of pattern in string, as a list of strings.

Pattern is

  • start followed by a space
  • the ( indicates the start of the part (group) we're interested in
  • the . indicates arbitrary character
  • the +? indicates at least one, but as little as possible
  • the ) indicates the end of the part (group) wer're interested in
  • a space followed by end.

The string is scanned left-to-right, and matches are returned in the order found.

If one or more groups are present in the pattern, return a list of groups;

We're using groups, as shown above

this will be a list of tuples if the pattern has more than one group.

We only use one group.

Empty matches are included in the result.

Sign up to request clarification or add additional context in comments.

1 Comment

This should also work fine str = [string.split("start")[1].strip() for string in str.split("end")[:-1]]. See it in action here.

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.