Skip to content Skip to sidebar Skip to footer

Split String On ". ","! " Or "? " Keeping The Punctuation Mark

Possible Duplicate: Python split() without removing the delimiter I wish to split a string as follows: text = ' T?e qu!ck ' brown 1 fox! jumps-.ver. the 'lazy' doG? !' res

Solution 1:

You can achieve this using a regular expression split:

>>> import re
>>> text = " T?e  qu!ck ' brown 1 fox! jumps-.ver. the 'lazy' doG?  !">>> re.split('(?<=[.!?]) +',text)
[" T?e  qu!ck ' brown 1 fox!", 'jumps-.ver.', "the 'lazy' doG?", '!']

The regular expression '(?<=[.!?]) +' means match a sequence of one or more spaces (' +') only if preceded by a ., ! or ? character ('(?<=[.!?])').

Post a Comment for "Split String On ". ","! " Or "? " Keeping The Punctuation Mark"