How to split a string (using regex?) depending on digit/ not digit

99封情书 提交于 2021-02-05 09:26:34

问题


I want to split a string into a list in python, depending on digit/ not digit. For example,

5 55+6+  5/

should return

['5','55','+','6','+','5','/']

I have some code at the moment which loops through the characters in a string and tests them using re.match("\d") or ("\D"). I was wondering if there was a better way of doing this.

P.S: must be compatible with python 2.4


回答1:


Assuming the + between 6 and 5 needs to be matched (which you're missing),

>>> import re
>>> s = '5 55+6+ 5/'
>>> re.findall(r'\d+|[^\d\s]+', s)
['5', '55', '+', '6', '+', '5', '/']



回答2:


this one is simplest one :)

re.findall('\d+|[^\d]+','134aaaaa')



回答3:


Use findall or finditer:

>>> re.findall(r'\d+|[^\s\d]+', '5 55+6+ 5/')
['5', '55', '+', '6', '+', '5', '/']



回答4:


If order doesn't matter, you could do 2 splits:

re.split('\D+', mystring)

re.split('\d+', mystring)

However, from your input, it looks like it might be mathematical... in which case order would matter. :)

You are best off using re.findall, as in one of the other answers.



来源:https://stackoverflow.com/questions/4218502/how-to-split-a-string-using-regex-depending-on-digit-not-digit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!