Search code examples
pythonlistsplit

Split a String with multiple delimiter and get the used delimiter


I want to split a String in python using multiple delimiter. In my case I also want the delimiter which was used returned in a list of delimiters.

Example:

string = '1000+20-12+123-165-564'

(Methods which split the string and return lists with numbers and delimiter)

  1. numbers = ['1000', '20', '12', '123', '165', '564']
  2. delimiter = ['+', '-', '+', '-', '-']

I hope my question is understandable.


Solution

  • Just capture (...) the delimiter along with matching/splitting with re.split:

    import re
    
    s = '1000+20-12+123-165-564'
    parts = re.split(r'([+-])', s)
    numbers, delims = parts[::2], parts[1::2]
    print(numbers, delims)
    

    ['1000', '20', '12', '123', '165', '564'] ['+', '-', '+', '-', '-']