如何根据数字/非数字分割字符串(使用正则表达式?)
我想在 python 中将一个字符串拆分为一个列表,具体取决于数字/而不是数字。 例如,
5 55+6+ 5/
应该返回
['5','55','+','6','+','5','/']
我目前有一些代码,它循环遍历字符串中的字符并使用 re.match("\d") 或 ("\D") 测试它们。我想知道是否有更好的方法来做到这一点。
PS:必须兼容python 2.4
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果顺序不重要,您可以进行 2 次拆分:
但是,从您的输入来看,它看起来可能是数学的......在这种情况下顺序很重要。 :)
你最好使用
re.findall
,就像其他答案之一一样。If order doesn't matter, you could do 2 splits:
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.使用
findall
或finditer
:Use
findall
orfinditer
:这是最简单的一个:)
this one is simplest one :)
假设 6 和 5 之间的
+
需要匹配(您缺少),Assuming the
+
between 6 and 5 needs to be matched (which you're missing),