Raghavendra Channappa
Raghavendra Channappa

Reputation: 77

Combine multiple re.sub into one

I am trying to remove spaces before and after '|' in a string.

This works:

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

I am trying to combine the two re.sub into one like this and result is not correct:

b = re.sub("(\s+\||\|\s+)", '|', s).strip()
print(b)

cat|  purr| dog|woof|cow|moo

Can someone help me with this?

P.S: I have tried using the split() function to separate the fields with '|' as the delimiter and then applying strip() function to each field and then assembling the string again. It works but seems tedious.

Upvotes: 1

Views: 545

Answers (1)

dragon2fly
dragon2fly

Reputation: 2419

You should use * quantifier for spaces to match zero or more space in one go.

print(re.sub('\s*\|\s*', '|', s))

# cat|purr|dog|woof|cow|moo

But for the case simple like this, a normal string replacement would do the job too.

print(s.replace(' ', '').replace('\t', ''))
# cat|purr|dog|woof|cow|moo

Upvotes: 1

Related Questions