如何根据数字/非数字分割字符串(使用正则表达式?)

发布于 2024-10-03 01:34:35 字数 268 浏览 6 评论 0原文

我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

吖咩 2024-10-10 01:35:29

如果顺序不重要,您可以进行 2 次拆分:

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

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

但是,从您的输入来看,它看起来可能是数学的......在这种情况下顺序很重要。 :)

你最好使用 re.findall ,就像其他答案之一一样。

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.

夏天碎花小短裙 2024-10-10 01:35:21

使用 findallfinditer

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

Use findall or finditer:

>>> re.findall(r'\d+|[^\s\d]+', '5 55+6+ 5/')
['5', '55', '+', '6', '+', '5', '/']
零度° 2024-10-10 01:35:13

这是最简单的一个:)

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

this one is simplest one :)

re.findall('\d+|[^\d]+','134aaaaa')
岁吢 2024-10-10 01:35:02

假设 6 和 5 之间的 + 需要匹配(您缺少),

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

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', '/']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文