有没有办法用下划线(或任何其他符号)替换字符串中的单个空格?

Edw*_*ese 2 python python-3.x

我可以编写一个def函数来完成此任务。但是,我想知道是否有任何方法可以像下面这样在一行中执行此任务string.replace('a',' ')

input  = "This   is a   regular text"

output = "This   is_a   regular_text"
Run Code Online (Sandbox Code Playgroud)

Aus*_*tin 5

使用正则表达式匹配单词之间的单个空格,并将其替换为下划线:

import re

inp  = "This   is a   regular text"
print(re.sub(r'(?<! ) (?! )', '_', inp))

# This   is_a   regular_text
Run Code Online (Sandbox Code Playgroud)