python - 替换python中单词之间的单个空格

标签 python regex replace

如何在 python 中将单词之间的单个空格替换为“_”?

例如:

输入:

09     Web Problem       Any problem has to do with the dept. web sites
12     SW Help           Questions about installed SW (hotline support)

输出:

09     Web_Problem       Any_problem_has_to_do_with_the_dept._web_sites
12     SW_Help           Questions_about_installed_SW_(hotline_support)

谢谢!

最佳答案

您可以使用正则表达式来执行此操作:

>>> import re
>>> x = '09     Web Problem       Any problem has to do with the dept. web sites'
>>> print re.sub(r'([^\s])\s([^\s])', r'\1_\2',x)
09     Web_Problem       Any_problem_has_to_do_with_the_dept._web_sites

搜索模式为 (1) 任何非空白字符,后跟 (2) 一个单个 空白字符,后跟 (3) 另一个非空白字符。

捕获数字 1 和 3,以便可以在替换模式中使用它们。数字 2 被忽略,我们用下划线代替。

这将单独保留多个空白区域,并简单地将单个出现的空白字符更改为下划线,这就是我认为您所要求的。

关于python - 替换python中单词之间的单个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9138471/

相关文章:

jquery - 是否可以获得选择表格翻转字符的正则表达式?

javascript - 替换部分属性值

python - 读取字符串位置

服务器上每个用户的 Python 进度条

python - 简化 numpy argmin 的愚蠢循环

regex - 数字范围的正则表达式生成器

c - 无法匹配 C 中的正则表达式

vim 无法查找和替换明显存在的简单短语

iphone - 将当前 View 替换为任何现有的新 View

python - 如何聚合 Pandas 数据框中的累积列表?