使用regex删除多余的空格

2024-05-29 05:58:06 发布

您现在位置:Python中文网/ 问答频道 /正文

产品名称:

"                Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)                  "

我有一个产品名称,在这个名称中,我需要删除“开始”之前和最后一个字符“)”之后的所有空格。正则表达式是我的必修课。我正试图用python实现这一切。你知道吗

注意:或者假设我只需要获取标题,不需要开始和结束空格。你知道吗


Tags: 名称air字符af空格whitewarrantybrand
3条回答

Remove extra spaces using regex

这不需要使用正则表达式。你知道吗

.strip()就是你需要的。你知道吗

print yourString.strip()
#Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)

实时PYTHON演示

http://ideone.com/iEmH0i


string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

如果你必须使用regex,你可以用这个:

import re
s = "                Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)                  "
s = re.sub("^\s+|\s+$","",s)
print(s)

结果:

"Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)"

只是为了好玩:一个使用regex的解决方案(因为这样更好strip

import re
p = re.compile('\s+((\s?\S+)+)\s+')
test_str = "                Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)                  "
subst = "\\1"

result = re.sub(p, subst, test_str)
print (result)

你得到了

Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)

相关问题 更多 >

    热门问题