如何在 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/