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

前端 未结 13 1248
[愿得一人]
[愿得一人] 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 03:42

    If you are splitting on newline, use splitlines(True).

    >>> 'line 1\nline 2\nline without newline'.splitlines(True)
    ['line 1\n', 'line 2\n', 'line without newline']
    

    (Not a general solution, but adding this here in case someone comes here not realizing this method existed.)

提交回复
热议问题