折叠字符串中的空格

pri*_*stc 8 python regex

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

"stuff   .  // : /// more-stuff .. .. ...$%$% stuff -> DD"
Run Code Online (Sandbox Code Playgroud)

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

"STUFF MORE STUFF STUFF DD"
Run Code Online (Sandbox Code Playgroud)

这可能是一个正则表达式还是我需要组合两个以上?这是我到目前为止:

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
Run Code Online (Sandbox Code Playgroud)

唯一不起作用的是空白崩溃.有任何想法吗?

Ale*_*lli 17

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

rex = re.compile(r'\W+')
result = rex.sub(' ', strarg).upper()
Run Code Online (Sandbox Code Playgroud)

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

  • @Brooks,你是对的——我非常反对隐藏内置和标准模块名称,除了字符串之外的任何东西都从我的指尖飞走。让我编辑来修复,谢谢! (2认同)

Joh*_*hin 5

s = "$$$aa1bb2 cc-dd ee_ff ggg."
re.sub(r'\W+', ' ', s).upper()
# ' AA1BB2 CC DD EE_FF GGG '
Run Code Online (Sandbox Code Playgroud)

是_标点符号?

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

不想要领先和尾随空间?

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