在 Python 中使用 Re 删除双 space/tab 组合

Remove double space/tab combinations using Re in Python

我想使用 Re 模块将 Python 中有连续制表符 and/or 空格的所有实例替换为单个空格。我不想删除新行(这排除了 \s 推荐)。目前我有:

    formateed_string = re.sub("\t+" , " ", formateed_string)            
    formateed_string = re.sub(" +" , " ", formateed_string)         
    formateed_string = re.sub("\t " , " ", formateed_string)    
    formateed_string = re.sub(" \t" , " ", formateed_string)

即首先检查连续的空格,然后是连续的制表符,然后是 tab/space,然后是 space/tab。这似乎通常有效,但偶尔会留下一个双倍空间(我猜这意味着 tabs/spaces 存在不寻常的污染,上面没有完全消除)。

是否有 simple/more 优雅的方法来实现这一点?

[n.b。运行 Python 2.7]

在正则表达式中,如果将字符放在方括号内,则表示 "any one of these characters"。所以 "[\t ]+" 将匹配任何制表符序列 and/or 空格。

formatted_string = re.sub("[\t ]+", " ", formatted_string)            

下面的正则表达式会将连续的制表符或 space 替换为单个白色 space。请注意,它不会将单个选项卡转换为 space.

formatted_string = re.sub("[\t ]{2,}", " ", formatted_string)