Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将多个re.sub合并为一个_Python 3.x_Regex - Fatal编程技术网

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'。只需要修剪'|'之前或之后的空格。