字符串中的空白折叠

10 投票
6 回答
9907 浏览
提问于 2025-04-15 13:35

我有一个字符串,大概长这样:

"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

唯一不成功的就是空格合并。有什么好主意吗?

6 个回答

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

因为你打错字了,第二次调用的时候忘记用了rex_s。还有,你需要至少替换一个空格回来,不然的话,多个空格会变成没有空格,也就是说会变成一个空格的间隔。

result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex_s.sub(' ', result) # this reduces all those spaces
7
s = "$$$aa1bb2 cc-dd ee_ff ggg."
re.sub(r'\W+', ' ', s).upper()
# ' AA1BB2 CC DD EE_FF GGG '

下划线算不算标点符号?

re.sub(r'[_\W]+', ' ', s).upper()
# ' AA1BB2 CC DD EE FF GGG '

不想要前后的空格吗?

re.sub(r'[_\W]+', ' ', s).strip().upper()
# 'AA1BB2 CC DD EE FF GGG'
19

这里有一个一步到位的方法(不过大写其实是用了一种字符串的方法——简单多了!):

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

其中 strarg 是字符串参数(请不要使用那些会覆盖内置函数或标准库模块的名字,谢谢)。

撰写回答