[英]How to split a string (using regex?) depending on digit/ not digit
我想將字符串拆分為python中的列表,具體取決於數字/不是數字。 例如,
5 55+6+ 5/
應該回來
['5','55','+','6','+','5','/']
目前,我有一些代碼可以循環遍歷字符串中的字符,並使用re.match(“ \\ d”)或(“ \\ D”)對其進行測試。 我想知道是否有更好的方法可以做到這一點。
PS:必須與python 2.4兼容
假設需要匹配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')
使用findall
或finditer
:
>>> re.findall(r'\d+|[^\s\d]+', '5 55+6+ 5/')
['5', '55', '+', '6', '+', '5', '/']
如果順序無關緊要,則可以進行2次拆分:
re.split('\D+', mystring)
re.split('\d+', mystring)
但是,從您的輸入看來,這似乎是數學上的……在這種情況下,順序很重要。 :)
與其他答案之一re.findall
,最好使用re.findall
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.