itailitai itailitai - 1 year ago 55
Python Question

How do I insert a whitespace after and before a dash that is not already followed by another whitespace?

Let's say I have these strings:

string1= "Queen -Bohemian Rhapsody"

string2= "Queen-Bohemian Rhapsody"

string3= "Queen- Bohemian Rhapsody"

I want all of them to become to be like this:

string1= "Queen - Bohemian Rhapsody"
string2= "Queen - Bohemian Rhapsody"
string3= "Queen - Bohemian Rhapsody"

How can I do this in Python?


Answer Source

You can regexp:

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download