python - 正则表达式:删除某些标点符号中的空格
问题描述
我有一些字符串,例如abc pre - school unit
orabc pre / school district
我需要在连字符和斜杠前后删除额外的空格。这些例子将变成abc pre-school unit
和abc 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)
解决方案
您可以捕获符号,然后替换为:
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
推荐阅读
- javascript - 一个易于使用的 JavaScript 库,用于在 Web 浏览器上绘制时间线?
- python - RobotFramework - 在 selenium2library 中无法识别使用自定义库打开的浏览器
- angular - 自动导航到 *ngFor? 中的第一个 routerLink?
- r - 将数据分组
- r - Apply `dplyr::rowwise` in all variables
- uwp - 如何在不使用动画(Composition Api)的情况下设置属性?
- git - 具有所有历史记录的 Perforce 流式传输到 Git 迁移
- java - 在一定延迟后需要帮助从 Web URL 下载文件
- scala - 如何将按第一个元素排序的元组列表分组到包含重叠和非重叠元组的两个列表中
- java - 为什么一定要加双引号?