Chianti5 Chianti5 - 3 months ago 9
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.
98/100
,
3/4
, and
5/6
as my final results.)

I know I should probably use
re
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

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'