![](/img/trans.png)
[英]Python Split a String using more than one character while still keeping that character
[英]python how to split string with more than one character?
我想如下分割一個字符串
1234ABC
變成123
和ABC
2B
成2
和B
10E
變成10
和E
我發現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.