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

后端 未结 2 1264
说谎
说谎 2020-12-06 12:42

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 w         


        
相关标签:
2条回答
  • 2020-12-06 12:48

    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?"
    
    0 讨论(0)
  • 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 [].

    0 讨论(0)
提交回复
热议问题