首页 > 解决方案 > 正则表达式:删除某些标点符号中的空格

问题描述

我有一些字符串,例如abc pre - school unitorabc pre / school district我需要在连字符和斜杠前后删除额外的空格。这些例子将变成abc pre-school unitabc pre/school district

我尝试了这个解决方案,但这只是用连字符替换斜杠或连字符。如何删除空格以获取这些字符串?

abc pre-school unit abc pre/school district

import re

text= ['abc pre - school unit', 'abc pre / school district']

for name in text:
    tmp= re.sub("\s+[-/]\s+" , "-", name)

    print(tmp)

标签: pythonregex

解决方案


您可以捕获符号,然后替换为:

text = ['abc pre - school unit', 'abc pre / school district']

for name in text:
    tmp = re.sub("\s+([/-])\s+" , "\\1", name)
    print(tmp)

这打印:

abc pre-school unit
abc pre/school district

推荐阅读