I want a function using regex that will map certain punctuation characters (these: .
, ,
, (
, )
, ;
, :
) to a function of that character. Specifically, it will put a space on either side.
For example, it would map the string "Hello, this is a test string." to "Hello , this is a test string . " This is what I have right now:
import re
def add_spaces_to_punctuation(input_text)
text = re.sub('[.]', ' . ', input_text)
text = re.sub('[,]', ' , ', text)
text = re.sub('[:]', ' : ', text)
text = re.sub('[;]', ' ; ', text)
text = re.sub('[(]', ' ( ', text)
text = re.sub('[)]', ' ) ', text)
return text
This works as intended, but is pretty unwieldy/hard to read. If I had a way to map each punctuation characters to a function of that character in a single regex line it would improve it significantly. Is there a way to do this with regex? Sorry if its something obvious, I'm pretty new to regex and don't know what this kind of thing would be called.