Skip to main content
 首页 » 编程设计

python之在 Python 中删除字符串中特定子字符串前后的字符

2025年05月04日27oomusou

我是 Python 的新手。可能这可以用正则表达式来完成。我想在字符串中搜索特定的子字符串并删除字符串中前后的字符。

示例 1

Input:"This is the consignment no 1234578TP43789" 
Output:"This is the consignment no TP" 

示例 2

Input:"Consignment no 1234578TP43789 is on its way on vehicle no 3456MP567890" 
Output:"Consignment no TP is on its way on vehicle no MP" 

我有要在字符串中搜索的这些缩写词(MP、TP)的列表。

请您参考如下方法:

你可以使用 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']