Home > Software design >  Split a String with multiple delimiter and get the used delimiter
Split a String with multiple delimiter and get the used delimiter

Time:02-01

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.

CodePudding user response:

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

CodePudding user response:

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