[英]Python match whitespaces
我试图删除一个字符串中的多个空格。 我已经阅读了python langauge中的正则表达式,并尝试使其与字符串中的所有白色空格匹配,但没有成功。 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!
re.match
仅在字符串的开头匹配。 您需要改用re.search
。
也许这段代码对您有帮助?
import re
def correct(string):
return " ".join(re.split(' *', string))
一线无直接进口
ss= "This is very funny and cool.Indeed!"
ss.replace(" ", " ")
#ss.replace(" ", " "*2)
#'This is very funny and cool.Indeed!'
或者,如问题所述:
ss= "This is very funny and cool.Indeed!"
ss.replace(" ", "")
#'Thisisveryfunnyandcool.Indeed!'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.