4

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

jfs
  • 399,953
  • 195
  • 994
  • 1,670
ebola virus
  • 117
  • 6

3 Answers3

6

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.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
3
import re
x="*abc*bbc"
print [x for x in re.split(r"(\*)",x) if x]

You have to use re.split and group the delimiter.

or

x="*abc*bbc"
print re.findall(r"[^*]+|\*",x)

Or thru re.findall

vks
  • 67,027
  • 10
  • 91
  • 124
2

Use partition();

a = "abc*bbc"
print (a.partition("*"))

>>> 
('abc', '*', 'bbc')
>>> 
GLHF
  • 3,835
  • 10
  • 38
  • 83