我想在選定的分隔符(一次很多)之后剪切串列元素:'-'、',' 和 ':'
我有一個示例串列:
list_1 = ['some text – some another', 'some text, some another', 'some text: some another']
我想剪切串列元素(在那種情況下是字串),以便它回傳以下輸出:
splitted_list = ['some text', 'some text', 'some text']
我已經嘗試過 split() 但一次只需要 1 個分隔符:
splited_list = [i.split(',', 1)[0] for i in list_1]
我更喜歡對我來說更容易理解的東西,并且我可以決定使用哪個分隔符。例如,我不想在之后-但在-.
分隔符串列:
: , -,,
注意-前后有空格,: 只有后有空格,就像, .
uj5u.com熱心網友回復:
您可以在其中使用此正則運算式re.sub并將其替換為空字串:
\s*[^\w\s].*
這將匹配 0 個或多個空格,后跟一個不是空格也不是單詞字符的字符以及之后的任何字符。
import re
list_1 = ['some text – some another', 'some text, some another', 'some text: some another']
delims = [',', ':', ' –']
delimre = '(' '|'.join(delims) r')\s.*'
splited_list = [re.sub(delimre, '', i) for i in list_1]
print (splited_list)
輸出:
['some text', 'some text', 'some text']
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/383642.html
上一篇:QRegEx匹配純色調顏色
