折叠字符串中的空白


问题内容

我有一个看起来像这样的字符串:

"stuff   .  // : /// more-stuff .. .. ...$%$% stuff -> DD"

我想删除所有标点符号,将所有内容都大写并折叠所有空格,使其看起来像这样:

"STUFF MORE STUFF STUFF DD"

一个正则表达式是否可以实现?还是我需要合并两个以上?这是我到目前为止所拥有的:

def normalize(string):
    import re

    string = string.upper()

    rex   = re.compile(r'\W')
    rex_s = re.compile(r'\s{2,}')

    result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
    result = rex.sub('', result) # this reduces all those spaces

    return result

唯一不起作用的是空白折叠。有任何想法吗?


问题答案:

这是一个单步方法(但是,大写实际上使用了字符串方法-简单得多!):

rex = re.compile(r'\W+')
result = rex.sub(' ', strarg).upper()

这里strarg是字符串参数( 使用名称影子建宏或标准库模块, )。