Dividing the string with multiple matches in python

Viewed 57

I have a string that has to be split for words that are present in "words"

words = ['word1', 'word2', 'word3']
text = " long statement word1 statement1 word2 statement2 word3 statement3 "  # a single lined string

The code I'm using, is there any simple way for this?

  for l in words:
        if l == "word1": t1 = text.split(l)
        if l == "word2": t2 = str(t1[1]).split(l)
        if l == "word3": t3 = str(t2[1]).split(l)
    
    print(t1[0])
    print(t2[0])
    print(t3[0])

The output is like:

statement
statement1
statement2
statement3
2 Answers

How about using itertools.groupby:

from itertools import groupby

words = ['word1', 'word2', 'word3']
text = " long statement word1 statement1 word2 statement2 word3 statement "
delimiters = set(words)
statements = [
    ' '.join(g) for k, g in groupby(text.split(), lambda w: w in delimiters)
    if not k
]
print(statements)

Output:

['long statement', 'statement1', 'statement2', 'statement3']

You could Regex for solving your problem in this way.

import re

words = ['word1', 'word2', 'word3']
text = " long statement word1 statement1 word2 statement2 word3 statement3 "
    
print(*re.split('|'.join(words),text), sep="\n")
Related