我有一个看起来像这样的字符串:
"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()
where strarg
是字符串参数 (don't使用隐藏内置函数或标准库模块的名称,please).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)