我正在尝试删除字符串中的多个空格。我读过 python 语言中的正则表达式,我试图让它匹配字符串中的所有 white-sapces,但没有成功。 return msg 部分返回空值:
代码
import re
def correct(string):
msg = ""
fmatch = re.match(r'\s', string, re.I|re.L)
if fmatch:
msg = fmatch.group
return msg
print correct("This is very funny and cool.Indeed!")
请您参考如下方法:
要完成此任务,您可以将连续的空格替换为单个空格字符,例如,使用 re.sub。
示例:
import re
def correct(string):
fmatch = re.sub(r'\s+', ' ', string)
return fmatch
print correct("This is very funny and cool.Indeed!")
输出将是:
This is very funny and cool.Indeed!
