Split a string by a delimiter in python


Question

How to split this string where __ is the delimiter

MATCHES__STRING

To get an output of ['MATCHES', 'STRING']?

1
167
11/18/2018 3:27:29 PM

Accepted Answer

You can use the str.split function: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']
282
10/9/2018 2:49:56 PM

You may be interested in the csv module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.

import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

for row in csv.reader( lines ):
    ...

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon