如何在python中拆分字符串并使用分隔符获取结果?

时间:2022-11-16 22:07:31

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

如何在python split函数或regex或分区中获取带分隔符的列表?我正在使用python 2.7,windows

3 个解决方案

#1


6  

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

您需要将RegEx与分隔符一起使用,并忽略空字符串,如下所示

>>> [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.

注1:您需要使用\来转义*,因为RegEx对*具有特殊含义。因此,您需要告诉RegEx引擎*应该被视为正常字符。

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.

注意2:当您将分隔符分隔开头或结尾处的字符串时,您将获得一个空字符串。检查此问题以了解其背后的原因。

#2


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.

您必须使用re.split并对分隔符进行分组。

or

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

Or thru re.findall

或者通过re.findall

#3


2  

Use partition();

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

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

#1


6  

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

您需要将RegEx与分隔符一起使用,并忽略空字符串,如下所示

>>> [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.

注1:您需要使用\来转义*,因为RegEx对*具有特殊含义。因此,您需要告诉RegEx引擎*应该被视为正常字符。

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.

注意2:当您将分隔符分隔开头或结尾处的字符串时,您将获得一个空字符串。检查此问题以了解其背后的原因。

#2


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.

您必须使用re.split并对分隔符进行分组。

or

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

Or thru re.findall

或者通过re.findall

#3


2  

Use partition();

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

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