python: padding punctuation with white spaces (keeping punctuation)

Viewed 17499

What is an efficient way to pad punctuation with whitespace?

input:

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

desired output:

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

Comments:

  1. I don't care how many whitespaces are there between tokens. (but they'll need to be collapsed eventually)
  2. I don't want to pad all punctuation. Say I'm interested only in .,!?().
3 Answers

If you use python3, use the maketrans() function.

import string   
text = text.translate(str.maketrans({key: " {0} ".format(key) for key in string.punctuation}))
Related