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

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

    Another no-regex solution that works well on Python 3

    # Split strings and keep separator
    test_strings = ['', 'Hi', ' ', '<', '']
    
    def split_and_keep(s, sep):
       if not s: return [''] # consistent with string.split()
    
       # Find replacement character that is not used in string
       # i.e. just use the highest available character plus one
       # Note: This fails if ord(max(s)) = 0x10FFFF (ValueError)
       p=chr(ord(max(s))+1) 
    
       return s.replace(sep, sep+p).split(p)
    
    for s in test_strings:
       print(split_and_keep(s, '<'))
    
    
    # If the unicode limit is reached it will fail explicitly
    unicode_max_char = chr(1114111)
    ridiculous_string = ''+unicode_max_char+''
    print(split_and_keep(ridiculous_string, '<'))
    

提交回复
热议问题