In Python, how do I split a string and keep the separators?

前端 未结 13 1236
[愿得一人]
[愿得一人] 2020-11-22 03:26

Here\'s the simplest way to explain this. Here\'s what I\'m using:

re.split(\'\\W\', \'foo/bar spam\\neggs\')
-> [\'foo\', \'bar\', \'spam\', \'eggs\']
         


        
13条回答
  •  無奈伤痛
    2020-11-22 04:00

    1. replace all seperator: (\W) with seperator + new_seperator: (\W;)

    2. split by the new_seperator: (;)

    def split_and_keep(seperator, s):
      return re.split(';', re.sub(seperator, lambda match: match.group() + ';', s))
    
    print('\W', 'foo/bar spam\neggs')
    

提交回复
热议问题