Python匹配空格

时间:2016-06-05 10:08:50

标签: python

我试图删除字符串中的多个空格。我已经阅读了python语言中的正则表达式,并且我试图使它匹配字符串中的所有白色sapces,但没有成功。 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!")

4 个答案:

答案 0 :(得分:3)

要完成此任务,您可以使用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!

答案 1 :(得分:2)

Undefined index: image仅匹配字符串的开头。您需要改为使用re.match

答案 2 :(得分:0)

也许这段代码可以帮到你?

import re

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

答案 3 :(得分:0)

一行没有直接导入

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