python: padding punctuation with white spaces (keeping punctuation)

前端 未结 3 880
青春惊慌失措
青春惊慌失措 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 19:56

    You can use a regular expression to match the punctuation characters you are interested and surround them by spaces, then use a second step to collapse multiple spaces anywhere in the document:

    s = 'bla. bla? bla.bla! bla...'
    import re
    s = re.sub('([.,!?()])', r' \1 ', s)
    s = re.sub('\s{2,}', ' ', s)
    print(s)
    

    Result:

    bla . bla ? bla . bla ! bla . . .
    

提交回复
热议问题