Search code examples
pythonstringsplitdelimiter

Split String with multiple delimiters and keep delimiters


I'm looking fo an elegenat way to split a string by multiple delimiters and keep the delimiters at which the string got splitted.

Example:

input_str = 'X < -500 & Y > 3000 / Z > 50'
split_str = re.split("and | or | & | /", input_str)
print split_str
>>> ['X < -500', ' Y > 3000',  'Z > 50']

What I want so get for split_str would be:

['X < -500', '&', ' Y > 3000', '/', 'Z > 50']

Solution

  • Try with parenthesis:

    >>> split_str = re.split("(and | or | & | /)", input_str)
    >>> split_str
    ['X < -500', ' & ', 'Y > 3000', ' /', ' Z > 50']
    >>> 
    

    If you want to remove extra spaces:

    >>> split_str = [i.strip() for i in re.split("(and | or | & | /)", input_str)]
    >>> split_str
    ['X < -500', '&', 'Y > 3000', '/', ' Z > 50']
    >>>