Search code examples
pythonstringlistsplit

Split a string by a delimiter in Python


Consider the following input string:

'MATCHES__STRING'

I want to split that string wherever the "delimiter" __ occurs. This should output a list of strings:

['MATCHES', 'STRING']

To split on whitespace, see How do I split a string into a list of words?.
To extract everything before the first delimiter, see Splitting on first occurrence.
To extract everything before the last delimiter, see Partition string in Python and get value of last segment after colon.


Solution

  • Use the str.split method:

    >>> "MATCHES__STRING".split("__")
    ['MATCHES', 'STRING']