ywat ywat - 27 days ago 5
Python Question

Insert spaces before and after special symbols in python

I want preprocess strings using Python.
Here is an example.

Given a string

string = "hello... (world)!"


I want to insert spaces before and after special characters like

desired_string = "hello . . . ( world ) !"


I find a way to do this by replace function.

string = string.replace(".", " . ")
string = string.replace("(", " ( ")
string = string.replace(")", " ) ")
string = string.replace("!", " ! ")


Then,

>>> string
'hello . . . ( world ) ! '


(This output string has more spaces than desired_string but is acceptable because I well apply
.split
method later.)

But the code is lengthy especially when many types of symbols appear. (e.g. !, @, $, %, &, ....)

I think there is a better way (maybe using
re.sub
?) Does anybody can show a better code?

Answer

using re adds white-space before and after the desired characters:

import re

pat = re.compile(r"([.()!])")
print (pat.sub(" \\1 ", string))
# hello .  .  .   ( world )  !