1

我无法解析包含字母和数字的字符串并返回列表。例如:

>>> 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']
4

2 回答 2

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']
于 2013-05-01T02:20:26.710 回答
2
>>> from re import split
>>> s = '1234gdfh1234'
>>> [i for i in split(r'(\d+)',s) if i]
['1234', 'gdfh', '1234']
于 2013-05-01T02:27:02.657 回答