Brian Fitzpatrick Brian Fitzpatrick - 6 months ago 8
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 '


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

Answer

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 '