python 如何拆分多于一个字符的字符串?

python how to split string with more than one character?

我想按如下方式拆分字符串

1234ABC 变成 123ABC

2B 变成 2B

10E 变成 10E

我发现split功能不起作用,因为没有delimiter

您可以将 itertools.groupby 与布尔 isdigit 函数一起使用。

from itertools import groupby

test1 = '123ABC'
test2 = '2B'
test3 = '10E'

def custom_split(s):
    return [''.join(gp) for _, gp in groupby(s, lambda char: char.isdigit())]

for t in [test1, test2, test3]:
    print(custom_split(t))

# ['123', 'ABC']
# ['2', 'B']
# ['10', 'E']

这可以使用 re 模块很容易地完成:

>>> import re
>>> 
>>> re.findall('[a-zA-Z]+|[0-9]+', '1234ABC')
['1234', 'ABC']
>>> re.findall('[a-zA-Z]+|[0-9]+', '2B')
['2', 'B']
>>> re.findall('[a-zA-Z]+|[0-9]+', '10E')
['10', 'E']
>>> # addtionall test case
... 
>>> re.findall('[a-zA-Z]+|[0-9]+', 'abcd1234efgh5678')
['abcd', '1234', 'efgh', '5678']
>>> 

正则表达式的使用非常简单。这是快速浏览:

  • [a-zA-Z]+:匹配一个或多个字母字符小写或大写
  • | 或...
  • [0-9]+: 一个或多个整数

另一种使用re包解决的方法

r = re.search('([0-9]*)([a-zA-Z]*)', test_string)
r.groups()