Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip whitespace from before but not after punctuation in python

Tags:

python

regex

relative python newbie here. I have a text string output from a program I can't modify. For discussion lets say:

text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"

I want to remove the space before the punctuation, but not remove the second space. I've been trying to do it with regex, and I know that I can match the instances I want using match='\s[\?.!\"]\s' as my search term.

x=re.search('\s[\?\.\!\"]\s',text)

Is there a way with a re.sub to replace the search term with the leading whitespace removed? Any ideas on how to proceed?

like image 932
B_Bigs Avatar asked Sep 18 '13 17:09

B_Bigs


2 Answers

Put a group around the text you want to keep and refer to that group by number in the replacement pattern:

re.sub(r'\s([?.!"](?:\s|$))', r'\1', text)

Note that I used a r'' raw string to avoid having to use too many backslashes; you didn't need to add quite so many, however.

I also adjusted the match for the following space; it now matches either a space or the end of the string.

Demo:

>>> import re
>>> text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"
>>> re.sub(r'\s([?.!"](?:\s|$))', r'\1', text)
"This text. Is to test. How it works! Will it! Or won't it? Hmm?"
like image 192
Martijn Pieters Avatar answered Sep 19 '22 09:09

Martijn Pieters


Use re.sub instead of re.search.

>>> text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"
>>> re.sub(r'\s+([?.!"])', r'\1', text)
"This text. Is to test. How it works! Will it! Or won't it? Hmm?"

You don't need to escape ?, ., !, " inside [] becaue special characters lose their meaning inside [].

like image 34
falsetru Avatar answered Sep 19 '22 09:09

falsetru