Michal K
Michal K

Reputation: 69

Splitting list elements after many delimiters

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]


I would prefer something which is more understandable for me and where I could decide which delimiter to use. For example, I don't want to cut string after - but after -.

List of delimiters:

: , - , ,

Note that - has space before and after, : only after, just like , .

Upvotes: 1

Views: 194

Answers (1)

anubhava
anubhava

Reputation: 786329

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']

Upvotes: 3

Related Questions