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?
using re adds white-space before and after the desired characters:
import re
pat = re.compile(r"([.()!])")
print (pat.sub(" \\1 ", string))
# hello . . . ( world ) !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With