Brian Fitzpatrick Brian Fitzpatrick - 8 months ago 14
Python Question

How can I trim the whitespace immediately preceding and following a given character in python?

I have a bunch of strings that look like this

s = '| this is | my | made up string '

I'd like to write a function that removes all the whitespace immediately preceeding and following the
's. So running
myFunc(s, '|')
would return

'|this is|my|made up string '

is too powerful, as I'd like to respect some of the whitespace. How can I do this in python?


Use regex replace.

import re

s = '| this is      |     my  | made up        string '
print(re.sub(r'\s*\|\s*', '|', s))

Will give this output -

'|this is|my|made up        string '