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

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

    I had a similar issue trying to split a file path and struggled to find a simple answer. This worked for me and didn't involve having to substitute delimiters back into the split text:

    my_path = 'folder1/folder2/folder3/file1'

    import re

    re.findall('[^/]+/|[^/]+', my_path)

    returns:

    ['folder1/', 'folder2/', 'folder3/', 'file1']

提交回复
热议问题