如何在尚未被空格包围的短划线之前和之前插入空格?

ita*_*tai 3 python regex string

假设我有这些字符串:

string1= "Queen -Bohemian Rhapsody"

string2= "Queen-Bohemian Rhapsody"

string3= "Queen- Bohemian Rhapsody"
Run Code Online (Sandbox Code Playgroud)

我希望他们所有人都变成这样:

   string1= "Queen - Bohemian Rhapsody"
   string2= "Queen - Bohemian Rhapsody"
   string3= "Queen - Bohemian Rhapsody"
Run Code Online (Sandbox Code Playgroud)

我怎么能用Python做到这一点?

谢谢!

abh*_*kdm 8

你可以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)
Run Code Online (Sandbox Code Playgroud)