[英]How to split a string (using regex?) depending on digit/ not digit
I want to split a string into a list in python, depending on digit/ not digit. 我想将字符串拆分为python中的列表,具体取决于数字/不是数字。 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"). 目前,我有一些代码可以循环遍历字符串中的字符,并使用re.match(“ \\ d”)或(“ \\ D”)对其进行测试。 I was wondering if there was a better way of doing this. 我想知道是否有更好的方法可以做到这一点。
PS: must be compatible with python 2.4 PS:必须与python 2.4兼容
Assuming the +
between 6 and 5 needs to be matched (which you're missing), 假设需要匹配6到5之间的+
(您丢失了),
>>> import re
>>> s = '5 55+6+ 5/'
>>> re.findall(r'\d+|[^\d\s]+', s)
['5', '55', '+', '6', '+', '5', '/']
这是最简单的一个:)
re.findall('\d+|[^\d]+','134aaaaa')
Use findall
or finditer
: 使用findall
或finditer
:
>>> re.findall(r'\d+|[^\s\d]+', '5 55+6+ 5/')
['5', '55', '+', '6', '+', '5', '/']
If order doesn't matter, you could do 2 splits: 如果顺序无关紧要,则可以进行2次拆分:
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. 与其他答案之一re.findall
,最好使用re.findall
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.