Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert spaces before and after special symbols in python

Tags:

python

string

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?

like image 274
ywat Avatar asked Oct 25 '25 05:10

ywat


1 Answers

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

import re

pat = re.compile(r"([.()!])")
print (pat.sub(" \\1 ", string))
# hello .  .  .   ( world )  ! 
like image 148
lycuid Avatar answered Oct 26 '25 18:10

lycuid