Home > front end >  Splitting list elements after many delimiters
Splitting list elements after many delimiters

Time:12-17

I would like to cut the list elements after a chosen delimiters(many at once): '-', ',' and ':'

I have an example list:


list_1 = ['some text – some another', 'some text, some another', 'some text: some another']

I'd like to cut the list elements(strings in that case) so that it will return the following output:

splitted_list = ['some text', 'some text', 'some text']

I already tried with split() but it only takes 1 delimiter at a time:

splited_list = [i.split(',', 1)[0] for i in list_1]

CodePudding user response:

You may use this regex in re.sub and replace it with an empty string:

\s*[^\w\s].*

This will match 0 or more whitespace followed by a character that is not a whitespace and not a word character and anything afterwards.

import re

list_1 = ['some text – some another', 'some text, some another', 'some text: some another']
delims = [',', ':', ' –']
delimre = '('   '|'.join(delims)   r')\s.*'
splited_list = [re.sub(delimre, '', i) for i in list_1]

print (splited_list)

Output:

['some text', 'some text', 'some text']
  • Related