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

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

    # This keeps all separators  in result 
    ##########################################################################
    import re
    st="%%(c+dd+e+f-1523)%%7"
    sh=re.compile('[\+\-//\*\<\>\%\(\)]')
    
    def splitStringFull(sh, st):
       ls=sh.split(st)
       lo=[]
       start=0
       for l in ls:
         if not l : continue
         k=st.find(l)
         llen=len(l)
         if k> start:
           tmp= st[start:k]
           lo.append(tmp)
           lo.append(l)
           start = k + llen
         else:
           lo.append(l)
           start =llen
       return lo
      #############################
    
    li= splitStringFull(sh , st)
    ['%%(', 'c', '+', 'dd', '+', 'e', '+', 'f', '-', '1523', ')%%', '7']
    

提交回复
热议问题