我在解析包含字母和数字的字符串并返回列表时遇到麻烦。例如:

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

最佳答案

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

关于python - Python-解析不包含字母和数字的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16311814/

10-10 21:51