How do I insert a space after and before a dash that is not already surrounded by spaces?
<p>Let's say I have these strings:</p>

<pre><code>string1= "Queen -Bohemian Rhapsody"

string2= "Queen-Bohemian Rhapsody"

string3= "Queen- Bohemian Rhapsody"
</code></pre>

<p>I want all of them to become to be like this:</p>

<pre><code>   string1= "Queen - Bohemian Rhapsody"
   string2= "Queen - Bohemian Rhapsody"
   string3= "Queen - Bohemian Rhapsody"
</code></pre>

<p>How can I do this in Python?</p>

<p>Thanks!</p>

<p>You can regexp:</p>

<pre><code>import re
pat = re.compile(r"\s?-\s?") # \s? matches 0 or 1 occurenece of white space

# re.sub replaces the pattern in string
string1 = re.sub(pat, " - ", string1)
string2 = re.sub(pat, " - ", string2)
string3 = re.sub(pat, " - ", string3)
</code></pre>

python regex string