Split a String with multiple delimiter and get the used delimiter

Question:

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.

Asked By: LordLazor

||

Answers:

You might use re.split for this task following way

import re
string = '1000+20-12+123-165-564'
elements = re.split(r'(d+)',string) # note capturing group
print(elements)  # ['', '1000', '+', '20', '-', '12', '+', '123', '-', '165', '-', '564', '']
numbers = elements[1::2] # last 2 is step, get every 2nd element, start at index 1
delimiter = elements[2::2] # again get every 2nd element, start at index 2
print(numbers)  # ['1000', '20', '12', '123', '165', '564']
print(delimiter)  # ['+', '-', '+', '-', '-', '']
Answered By: Daweo

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'] ['+', '-', '+', '-', '-']
Answered By: RomanPerekhrest
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.