Python - 解析一个字母和数字不被阻塞的字符串

时间:2013-05-01 02:16:44

标签: python parsing

我在解析包含字母和数字的字符串并获取列表时遇到问题。例如:

>>> s = '105Bii2016'
>>> foo(s)
['105', 'Bii', '2016']

现在我只能在数字合在一起时才能这样做:

def foo(s):
    num, letter = '', ''
    for i in s:
        if i.isdigit():
            num += i
        else:
            letter += i
    return [letter, num]

当我这样称呼时:

>>> s = '1234gdfh1234'

>>> foo(s)

['gdfh', '12341234']

2 个答案:

答案 0 :(得分:6)

itertools.groupby

怎么样?
>>> s = '1234gdfh1234'
>>> from itertools import groupby
>>> print [''.join(v) for k,v in groupby(s,str.isdigit)]
['1234', 'gdfh', '1234']

另一种解决方案使用正则表达式:

>>> print [x for x in re.split(r'(\d+)',s) if x]
['1234', 'gdfh', '1234']

答案 1 :(得分:2)

>>> from re import split
>>> s = '1234gdfh1234'
>>> [i for i in split(r'(\d+)',s) if i]
['1234', 'gdfh', '1234']