我想知道以以下方式分隔字符串中数字的最简单方法(可能是正则表达式)是什么。示例:"abc12de34f5"
到:["abc", "12", "de", "34", "f", "5"]
但是,如果字符串中有连接标记,请以这种方式分隔:示例:"abc1,2de3.4f5"
to:["abc", "1,2", "de", "3.4", "f", "5"]
感谢您的任何建议和意见
>>> import re
>>> s = "abc12de34f5"
>>> re.findall(r'[\d\W]+|[a-zA-Z]+', s)
['abc', '12', 'de', '34', 'f', '5']
>>> t = "abc1,2de3.4f5"
>>> re.findall(r'[\d\W]+|[a-zA-Z]+', t)
['abc', '1,2', 'de', '3.4', 'f', '5']
使用 itertools.groupby 的非正则表达式解决方案
>>> st = "abc1,2de3.4f5"
>>> [''.join(v) for _, v in groupby(st,key = str.isalpha)]
['abc', '1,2', 'de', '3.4', 'f', '5']
>>> st = "abc12de34f5"
>>> [''.join(v) for _, v in groupby(st,key = str.isalpha)]
['abc', '12', 'de', '34', 'f', '5']