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

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

    Here is a simple .split solution that works without regex.

    This is an answer for Python split() without removing the delimiter, so not exactly what the original post asks but the other question was closed as a duplicate for this one.

    def splitkeep(s, delimiter):
        split = s.split(delimiter)
        return [substr + delimiter for substr in split[:-1]] + [split[-1]]
    

    Random tests:

    import random
    
    CHARS = [".", "a", "b", "c"]
    assert splitkeep("", "X") == [""]  # 0 length test
    for delimiter in ('.', '..'):
        for _ in range(100000):
            length = random.randint(1, 50)
            s = "".join(random.choice(CHARS) for _ in range(length))
            assert "".join(splitkeep(s, delimiter)) == s
    

提交回复
热议问题