re函數split各種情況

前言

Python版本:3.7.4

split(pattern, string, maxsplit=0, flags=0)
原文
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings. If
capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list. If maxsplit is nonzero, at most maxsplit splits occur,
and the remainder of the string is returned as the final element
of the list.
就是
根據pattern分割文本
當使用【捕捉括號】時,所有組都會返回
maxsplit限制最大切割次數,默認無限切
最終返回list

一般情況

from re import split
a = split(',', 'aa,bb')
print(a)

['aa', 'bb']

限制切割次數

from re import split
a = split(',', 'aa,bb,cc', 1)
print(a)

['aa', 'bb,cc']

結果出現’’

from re import split
a = split(',', ',aa,,bb,')
print(a)

['', 'aa', '', 'bb', '']

pattern使用括號

from re import split
a = split('(,)', 'aa,')
print(a)

['aa', ',', '']

pattern使用多重括號

from re import split
a = split('aa(bb(cc))', 'ZaabbccZ')
print(a)

['Z', 'bbcc', 'cc', 'Z']

patter同時用 () 和 | 會出現None

from re import split
a = split(',|(;)', 'aa,bb;cc')
print(a)

['aa', None, 'bb', ';', 'cc']

排除空值的寫法

from re import split
a = [i for i in split(',|(;)', ',aa,;bb,')if i]
print(a)

['aa', ';', 'bb']

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章