Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex inserting a space between punctuation and letters

I assume the best way to do this is with regex but I do not know how to do it. I am trying to parse a string and put a space between letters and punctuation only. I want to keep punctuation marks together. As an example if I have the string

"yes!!!"

I want to end up with

"yes", "!!!".

If I have the string

!!!N00bs,

I want to end up with

"!!!", "N00bs"

Is this possible? What is the best way to do this? Right now I am parsing each letter and it a silly way of doing it.

Thanks for the help.

like image 457
English Grad Avatar asked Dec 20 '13 14:12

English Grad


1 Answers

something like this:

txt = re.sub( r'([a-zA-Z])([,.!])', r'\1 \2', '!!!this, .is, .a .test!!!' )

you can switch the order for the other direction

re.sub( r'([,.!])([a-zA-Z])', r'\1 \2', txt )

probably you can also make it work in one regex as well

like image 148
behzad.nouri Avatar answered Sep 20 '22 22:09

behzad.nouri