Python 3.x 将多个re.sub合并为一个
我试图删除字符串中“|”前后的空格 这项工作:Python 3.x 将多个re.sub合并为一个,python-3.x,regex,Python 3.x,Regex,我试图删除字符串中“|”前后的空格 这项工作: s = 'cat | purr | dog |woof| cow| moo' a = re.sub('\s+\|', '|', s).strip() b= re.sub('\|\s+', '|', a) print(b) cat|purr|dog|woof|cow|moo 我试图将两个re.sub合并为一个,结果不正确: b = re.sub("(\s+\||\|\s+)", '|', s).str
s = 'cat | purr | dog |woof| cow| moo'
a = re.sub('\s+\|', '|', s).strip()
b= re.sub('\|\s+', '|', a)
print(b)
cat|purr|dog|woof|cow|moo
我试图将两个re.sub合并为一个,结果不正确:
b = re.sub("(\s+\||\|\s+)", '|', s).strip()
print(b)
cat| purr| dog|woof|cow|moo
有人能帮我吗
注:我尝试过使用split()函数来分隔以“|”为分隔符的字段,然后对每个字段应用strip()函数,然后再次组合字符串。它可以工作,但看起来很乏味。您应该使用
*
量词来表示空格,以便一次匹配零个或多个空格
print(re.sub('\s*\|\s*', '|', s))
# cat|purr|dog|woof|cow|moo
但是对于这样简单的情况,一个普通的字符串替换也可以完成这项工作
print(s.replace(' ', '').replace('\t', ''))
# cat|purr|dog|woof|cow|moo
正则表达式起作用了。谢谢简单替换也将删除字符串中的空格(我需要'd og'保持为'd og'。只需要修剪'|'之前或之后的空格。