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>You can remove whitespace before and after slashes with <code>str.replace</code> instead of regex:</p>

<pre><code>&gt;&gt;&gt; '98 / 100 xx 3/ 4 and 5/6'.replace(' /','/').replace('/ ','/')
'98/100 xx 3/4 and 5/6'
</code></pre>

python regex