Python匹配空格

Python匹配空格,python,Python,我试图删除字符串中的多个空格。我读过python langauge中的正则表达式,我试图使它匹配字符串中的所有白色sapce,但没有成功。返回消息部分返回空: 代码 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("T

我试图删除字符串中的多个空格。我读过python langauge中的正则表达式,我试图使它匹配字符串中的所有白色sapce,但没有成功。
返回消息
部分返回空:

代码

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.match
仅在字符串开头匹配。您需要改用
re.search

re.match
仅在字符串开头匹配。您需要使用
re.search

要完成此任务,您可以使用单个空格字符替换连续的空格,例如,使用
re.sub

例如:

输出将是:

This is very funny and cool.Indeed!

要完成此任务,可以使用单个空格字符替换连续的空格,例如,使用
re.sub

例如:

输出将是:

This is very funny and cool.Indeed!

也许这个代码对你有帮助

import re

def correct(string):
    return " ".join(re.split(' *', string))

也许这个代码对你有帮助

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!'

一行不能直接导入

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!'

所以我把它改成了
re.search(r'\s',string,re.i | re.L)
并得到了这个消息:是的,
group
是一个方法,你需要调用它。所以我把它改成了
re.search(r'\s',string,re.i | re.L)
并得到了这个消息:是的,
group
是一个方法,你需要调用它。我可以添加另一个表达式来查找吗。(点)?并将其替换为+space@IdontReallywolf所以你想用
替换
?是的,您可以,以类似的方式,我必须创建一个新行,还是可以将表达式添加到当前行中?您必须以不同的方式进行另一个
sub
调用line@IdontReallywolf,您可以这样做:
re.sub(r'\s+','',s.replace('.',')
,其中
s
是您的字符串。PS不要使用诸如
string
list
dict
等保留字作为变量名称-这将有助于避免将来出现问题。我可以添加另一个表达式来查找吗。(点)?并将其替换为+space@IdontReallywolf所以你想用
替换
?是的,您可以,以类似的方式,我必须创建一个新行,还是可以将表达式添加到当前行中?您必须以不同的方式进行另一个
sub
调用line@IdontReallywolf,您可以这样做:
re.sub(r'\s+','',s.replace('.',')
,其中
s
是您的字符串。PS不要使用诸如
string
list
dict
等保留字作为变量名称-这将有助于避免将来出现问题。