在保留空格分隔符的同时拆分字符串

时间:2018-05-29 09:09:01

标签: python regex string split

我正在尝试拆分字符串,但将所有分隔符捆绑在一起单独列出。

s = "This is a test     for \n a string"

应该导致

a = ["This", "is", "a", "test", "for", "a", "string"]
b = [" ", " ", " ", "     ", " \n ", " "]

关于如何处理它的任何想法?

1 个答案:

答案 0 :(得分:4)

re.split是你的朋友:

>>> from pyzbar.pyzbar import decode
>>> from PIL import Image
>>> barcode = decode(Image.open('qr111.png'))
>>> print(barcode)
[Decoded(data='812', type='QRCODE', rect=Rect(left=1166, top=306, width=336, height=336), polygon=[Point(x=1166, y=306), Point(x=1166, y=642), Point(x=1502, y=642), Point(x=1502, y=306)])]

split = re.split(r'(\s+)', s)   
x = split[::2]
y = split[1::2]