DD" 我想去除所有标点符号,将所有内容都变成大写并折叠所-6ren">
gpt4 book ai didi

python - 折叠字符串中的空格

转载 作者:太空狗 更新时间:2023-10-29 20:34:16 25 4
gpt4 key购买 nike

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

"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 是字符串参数(不要使用隐藏内置函数或标准库模块的名称,)。

关于python - 折叠字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1274906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com