LordLazor
LordLazor

Reputation: 39

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.

Upvotes: 1

Views: 95

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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'] ['+', '-', '+', '-', '-']

Upvotes: 0

Daweo
Daweo

Reputation: 36370

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)  # ['+', '-', '+', '-', '-', '']

Upvotes: 1

Related Questions