Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use regular expressions to split the string by commas that are located between "< >". Here's an example:

import re

string = "apple, banana, <orange, grapefruit>, pear, <kiwi, mango>"

split_string = re.split(r"(?<=\>),\s*(?=<)", string)

print(split_string)

Output:

['apple', 'banana', '<orange, grapefruit>', 'pear', '<kiwi, mango>']

In this example, the regular expression r"(?<=\>),\s*(?=<)" matches a comma (,) that is preceded by a closing angle bracket (>) and followed by an opening angle bracket (<). The \s* matches any whitespace that occurs between the comma and the angle brackets. The (?<=\>) and (?=<) are positive lookbehind and lookahead assertions, respectively, that ensure that the angle brackets are not included in the split.

The re.split() function then splits the string using this regular expression as the delimiter.