Fix Python – Python split() without removing the delimiter [duplicate]

Question

Asked By – some1

This code almost does what I need it to..

for line in all_lines:
    s = line.split('>')

Except it removes all the ‘>’ delimiters.

So,

<html><head>

Turns into

['<html','<head']

Is there a way to use the split() method but keep the delimiter, instead of removing it?

With these results..

['<html>','<head>']

Now we will see solution for issue: Python split() without removing the delimiter [duplicate]


Answer

d = ">"
for line in all_lines:
    s =  [e+d for e in line.split(d) if e]

This question is answered By – P.Melch

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0