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

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

    another example, split on non alpha-numeric and keep the separators

    import re
    a = "foo,bar@candy*ice%cream"
    re.split('([^a-zA-Z0-9])',a)
    

    output:

    ['foo', ',', 'bar', '@', 'candy', '*', 'ice', '%', 'cream']
    

    explanation

    re.split('([^a-zA-Z0-9])',a)
    
    () <- keep the separators
    [] <- match everything in between
    ^a-zA-Z0-9 <-except alphabets, upper/lower and numbers.
    

提交回复
热议问题