您可以使用re.sub
>>> string="This is the consignment no 1234578TP43789"
>>> re.sub(r'\d+(TP|MP)\d+', r'\1', string)
'This is the consignment no TP'
>>> string="Consignment no 1234578TP43789 is on its way on vehicle no 3456MP567890"
>>> re.sub(r'\d+(TP|MP)\d+', r'\1', string)
'Consignment no TP is on its way on vehicle no MP'
它能做什麼?
\d+
匹配一個或多個數字。
(TP|MP)
匹配TP
或MP
。在\1
中捕獲它。我們使用這個捕獲的字符串來替換整個匹配的字符串。
如果可以出現任何字符之前和TP/MP之後,我們就可以使用\S
匹配一個空格其他任何東西。例如,
>>> string="Consignment no 1234578TP43789 is on its way on vehicle no 3456MP567890"
>>> re.sub(r'\S+(TP|MP)\S+', r'\1', string)
'Consignment no TP is on its way on vehicle no MP'
編輯
使用list comprehension,你可以遍歷列表和替換所有的字符串作爲,
>>> list_1=["TP","MP","DCT"]
>>> list_2=["This is the consignment no 1234578TP43789","Consignment no 1234578TP43789 is on its way on vehicle no 3456MP567890"]
>>> [ re.sub(r'\d+(' + '|'.join(list_1) + ')\d+', r'\1', string) for string in list_2 ]
['This is the consignment no TP', 'Consignment no TP is on its way on vehicle no MP']
看看正則表達式模塊的替換功能,[應用re.sub](HTTPS內://文檔.python.org/3.5/library/re.html#re.sub) – Olian04
TP之前和之後。它可以同時包含數字和字符。這個東西1234578TP43789應該被輸出中的TP代替。 –