Brian Fitzpatrick Brian Fitzpatrick - 2 years ago 79
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?

Answer Source

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 '    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download