[英]Python match whitespaces
Im trying to remove multiple white-spaces in a string. 我试图删除一个字符串中的多个空格。 I've read about regular expressions in python langauge and i've tried to make it match all white-sapces in the string, but no success.
我已经阅读了python langauge中的正则表达式,并尝试使其与字符串中的所有白色空格匹配,但没有成功。 The
return msg
part returns empty: return msg
部分返回空:
CODE 码
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!")
To accomplish this task, you can instead replace consecutive whitespaces with a single space character, for example, using re.sub
. 要完成此任务,您可以使用单个空格字符代替连续的空格,例如,使用
re.sub
。
Example: 例:
import re
def correct(string):
fmatch = re.sub(r'\s+', ' ', string)
return fmatch
print correct("This is very funny and cool.Indeed!")
The output will be: 输出将是:
This is very funny and cool.Indeed!
re.match
matches only at the beginning of the string. re.match
仅在字符串的开头匹配。 You need to use re.search
instead. 您需要改用
re.search
。
Maybe this code helps you? 也许这段代码对您有帮助?
import re
def correct(string):
return " ".join(re.split(' *', string))
One line no direct import 一线无直接进口
ss= "This is very funny and cool.Indeed!"
ss.replace(" ", " ")
#ss.replace(" ", " "*2)
#'This is very funny and cool.Indeed!'
Or, as the question states: 或者,如问题所述:
ss= "This is very funny and cool.Indeed!"
ss.replace(" ", "")
#'Thisisveryfunnyandcool.Indeed!'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.