HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Split string with multiple delimiters in Python

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
multiplesplitpythonstringdelimiterswith

Problem

I found some answers online, but I have no experience with regular expressions, which I believe is what is needed here.

I have a string that needs to be split by either a ';' or ', '
That is, it has to be either a semicolon or a comma followed by a space. Individual commas without trailing spaces should be left untouched

Example string:

"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]"


should be split into a list containing the following:

('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]')

Solution

Luckily, Python has this built-in :)

import re

# Regex pattern splits on substrings "; " and ", "
re.split('; |, ', string_to_split)


Update:

Following your comment:

>>> string_to_split = 'Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n', string_to_split)
['Beautiful', 'is', 'better', 'than', 'ugly']

Code Snippets

import re

# Regex pattern splits on substrings "; " and ", "
re.split('; |, ', string_to_split)
>>> string_to_split = 'Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n', string_to_split)
['Beautiful', 'is', 'better', 'than', 'ugly']

Context

Stack Overflow Q#4998629, score: 1339

Revisions (0)

No revisions yet.