Suyang Wang
Suyang Wang

Reputation: 21

Python re.split: how to preserve patten

In python codes are:

list = "a123,145B,12"
re.split("[a-zA-Z_]",list)

Result:

['', '123,145', ',12']

How can I preserve characters, so the result will be:

['a','123,145','B',',12']

Upvotes: 2

Views: 64

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

You can use a capture group :

>>> re.split("([a-zA-Z_])",li)
['', 'a', '123,145', 'B', ',12']

And for get ride of empty string you can use filter built-in function :

>>> filter(bool,re.split("([a-zA-Z_])",li))
['a', '123,145', 'B', ',12']

Upvotes: 1

Related Questions