python: padding punctuation with white spaces (keeping punctuation)

前端 未结 3 896
青春惊慌失措
青春惊慌失措 2021-02-05 19:16

What is an efficient way to pad punctuation with whitespace?

input:

s = \'bla. bla? bla.bla! bla...\'

desired output:

          


        
3条回答
  •  故里飘歌
    2021-02-05 20:13

    This will add exactly one space if one is not present, and will not ruin existing spaces or other white-space characters:

    s = re.sub('(?

    This works by finding a zero-width position between a punctuation and a non-space, and adding a space there.
    Note that is does add a space on the beginning or end of the string, but it can be easily done by changing the look-arounds to (?<=[^ ]) and (?=[^ ]).

    See in in action: http://ideone.com/BRx7w

提交回复
热议问题