Chianti5 Chianti5 - 1 year ago 60
Python Question

Python conditionally remove whitespaces

I want to remove whitespaces in a string that are adjacent to

while keeping the rest of the whitespaces.

For instance, say I have a string
98 / 100 xx 3/ 4 and 5/6
. The desired result for my example would be
98/100 xx 3/4 and 5/6
. (So that I could use
.split(' ')
as a next step and extract those meaningful numbers, i.e.
, and
as my final results.)

I know I should probably use
for this, but I can't figure it out. Any help is appreciated!

---------------------My Approach Below------------------

I used
[index_num.end(0) for index_num in re.finditer('/', test)]
, where
test = '98 / 100 xx 3/ 4 and 5/6'
to find the index of the
, then check if the previous or the next is a whitespace. That's not ideal and I believe there are easier ways.

Answer Source

You can remove whitespace before and after slashes with str.replace instead of regex:

>>> '98 / 100 xx 3/ 4 and 5/6'.replace(' /','/').replace('/ ','/')
'98/100 xx 3/4 and 5/6'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download