How to add space before and after specific character using regex in Python?


The following code shows how space is added before and after the pipe '|' character in given string. 

Example

import re
regex = r'\b[|:]\b'
s = "abracadabra abraca|dabara | abra cadabra abra ca dabra abra ca dabra abra"
print(re.sub(regex, ' \g<0> ', s))

Output

This gives the output

abracadabra abraca | dabara | abra cadabra abra ca dabra abra ca dabra abra

Updated on: 18-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements