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

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

    If you have only 1 separator, you can employ list comprehensions:

    text = 'foo,bar,baz,qux'  
    sep = ','
    

    Appending/prepending separator:

    result = [x+sep for x in text.split(sep)]
    #['foo,', 'bar,', 'baz,', 'qux,']
    # to get rid of trailing
    result[-1] = result[-1].strip(sep)
    #['foo,', 'bar,', 'baz,', 'qux']
    
    result = [sep+x for x in text.split(sep)]
    #[',foo', ',bar', ',baz', ',qux']
    # to get rid of trailing
    result[0] = result[0].strip(sep)
    #['foo', ',bar', ',baz', ',qux']
    

    Separator as it's own element:

    result = [u for x in text.split(sep) for u in (x, sep)]
    #['foo', ',', 'bar', ',', 'baz', ',', 'qux', ',']
    results = result[:-1]   # to get rid of trailing
    

提交回复
热议问题