我有一个字符串,看起来像这样:
"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
是字符串参数(不使用阴影建宏或标准库模块,名称请).
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)
归档时间: |
|
查看次数: |
5970 次 |
最近记录: |