从字符串中的数字拆分字母

Cod*_*Cat 10 python string split

我正在处理这样的字符串:"125A12C15" 我需要在字母和数字之间的边界处将它们分开,例如,这应该成为["125","A","12","C","15"].

有没有更优雅的方法在Python中执行此操作,而不是通过位置检查它是否是一个字母或数字,然后相应地连接?例如,这种东西的内置功能或模块?

感谢您的任何指示!

roo*_*oot 28

使用itertools.groupby连同str.isalpha方法:

文档字符串:

groupby(iterable [,keyfunc]) - >创建一个迭代器,它返回(key,sub-iterator)按键(值)的每个值分组.


文档字符串:

S.isalpha() - > bool

如果S中的所有字符都是字母并且S中至少有一个字符,则返回True,否则返回False.


In [1]: from itertools import groupby

In [2]: s = "125A12C15"

In [3]: [''.join(g) for _, g in groupby(s, str.isalpha)]
Out[3]: ['125', 'A', '12', 'C', '15']
Run Code Online (Sandbox Code Playgroud)

或可能re.findallre.split正则表达式模块:

In [4]: import re

In [5]: re.findall('\d+|\D+', s)
Out[5]: ['125', 'A', '12', 'C', '15']

In [6]: re.split('(\d+)', s)  # note that you may have to filter out the empty
                              # strings at the start/end if using re.split
Out[6]: ['', '125', 'A', '12', 'C', '15', '']

In [7]: re.split('(\D+)', s)
Out[7]: ['125', 'A', '12', 'C', '15']
Run Code Online (Sandbox Code Playgroud)

至于性能,似乎使用正则表达式可能更快:

In [8]: %timeit re.findall('\d+|\D+', s*1000)
100 loops, best of 3: 2.15 ms per loop

In [9]: %timeit [''.join(g) for _, g in groupby(s*1000, str.isalpha)]
100 loops, best of 3: 8.5 ms per loop

In [10]: %timeit re.split('(\d+)', s*1000)
1000 loops, best of 3: 1.43 ms per loop
Run Code Online (Sandbox Code Playgroud)