繁体   English   中英

python如何用多个字符分割字符串?

[英]python how to split string with more than one character?

我想如下分割一个字符串

1234ABC变成123ABC

2B2B

10E变成10E

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

您可以将itertools.groupby与boolean 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]+ :一个或多个整数

解决这个问题的另一种方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM