Python conditionally remove whitespaces
<p>I want to remove whitespaces in a string that are adjacent to <code>/</code> while keeping the rest of the whitespaces.</p>

<p>For instance, say I have a string <code>98 / 100 xx 3/ 4 and 5/6</code>. The desired result for my example would be <code>98/100 xx 3/4 and 5/6</code>. (So that I could use <code>.split(' ')</code> as a next step and extract those meaningful numbers, i.e.<code>98/100</code>, <code>3/4</code>, and <code>5/6</code> as my final results.) Note: I only want to look for <code>/</code>, no need to worry other operators.</p>

<p>I know I should probably use <code>re</code> for this, but I can't figure it out. Any help is appreciated! </p>

<p>---------------------My Approach Below------------------</p>

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

<p>A hint: A regular expression that will find any amount of whitespace (not just space characters, but also tabs, etc.) around a slash is: <code>r'\s*/\s*'</code>. The regex there is between the apostrophes. The period is just the end of my sentence, and the r tells Python to treat the string inside apostrophes as a "raw" string.</p>

<p>If you don't want to find arbitrary whitespace characters, but only the space character itself, the regex is <code>r' */ *'</code>. Note the space in front of the asterisk.</p>

<p>The rest I leave to you, since this sounds like a homework problem.</p>

python regex