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

2024-04-20 13:57:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在Python中,有没有比逐个检查它的位置并检查它是一个字母还是一个数字,然后相应地连接起来更优雅的方法呢?E、 g.这种东西的内置函数或模块?

谢谢你的指点!


Tags: 模块方法函数字符串字母数字内置边界
1条回答
网友
1楼 · 发布于 2024-04-20 13:57:32

^{}^{}方法一起使用:

Docstring:

groupby(iterable[, keyfunc]) -> create an iterator which returns (key, sub-iterator) grouped by each value of key(value).


Docstring:

S.isalpha() -> bool

Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.


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

或者可能来自regular expressions modulere.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']

至于性能,使用regex可能更快:

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

相关问题 更多 >