Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can split string in python and get result with delimiter?

I have code like

a = "*abc*bbc"
a.split("*")#['','abc','bbc']
#i need ["*","abc","*","bbc"] 
a = "abc*bbc"
a.split("*")#['abc','bbc']
#i need ["abc","*","bbc"]

How can i get list with delimiter in python split function or regex or partition ? I am using python 2.7 , windows

like image 803
ebola virus Avatar asked Dec 19 '22 06:12

ebola virus


1 Answers

You need to use RegEx with the delimiter as a group and ignore the empty string, like this

>>> [item for item in re.split(r"(\*)", "abc*bbc") if item]
['abc', '*', 'bbc']
>>> [item for item in re.split(r"(\*)", "*abc*bbc") if item]
['*', 'abc', '*', 'bbc']

Note 1: You need to escape * with \, because RegEx has special meaning for *. So, you need to tell RegEx engine that * should be treated as the normal character.

Note 2: You ll be getting an empty string, when you are splitting the string where the delimiter is at the beginning or at the end. Check this question to understand the reason behind it.

like image 135
thefourtheye Avatar answered Dec 21 '22 20:12

thefourtheye