簡體   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