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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

filter(None, re.split('([*])', '*abc*bbc'))
@hwnd Actually, List Comprehension is preferred over the filter in Python :)
Yes, preferred but still not bad =)
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

Comments

2

Use partition();

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

>>> 
('abc', '*', 'bbc')
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.