Split a string by a delimiter in python

461,773

Solution 1

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

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

Solution 2

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 ):
    ...

Solution 3

When you have two or more elements in the string (in the example below there are three), then you can use a comma to separate these items:

date, time, event_name = ev.get_text(separator='@').split("@")

After this line of code, the three variables will have values from three parts of the variable ev.

So, if the variable ev contains this string and we apply separator @:

Sa., 23. März@19:00@Klavier + Orchester: SPEZIAL

Then, after the split operation the variable

  • date will have value Sa., 23. März
  • time will have value 19:00
  • event_name will have value Klavier + Orchester: SPEZIAL
Share:
461,773

Related videos on Youtube

Hulk
Author by

Hulk

Updated on April 12, 2022

Comments

  • Hulk
    Hulk about 2 years

    How to split this string where __ is the delimiter

    MATCHES__STRING
    

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

    • getekha
      getekha over 13 years
    • Tony Veijalainen
      Tony Veijalainen over 13 years
      It is worth to read the python standard documents and trying to understand few programs others have made to start to grasp basics of Python. Practise and copying/modifying are great tools to learn language.
  • EndenDragon
    EndenDragon almost 8 years
    I was wondering, what is the difference between the first example (simply using split()) and the second example (with a for loop)?
  • Sébastien Vercammen
    Sébastien Vercammen almost 8 years
    @EndenDragon The for loop will automatically apply x.strip() and return a list of matches without whitespace on either side. The devil is in the details.
  • Aran-Fey
    Aran-Fey over 5 years
    Hey, since this is a very popular question, I edited it to ask only 1 specific question and removed the part with the spaces around the delimiter because it wasn't clear what the OP even expected to happen (Since there never was a question in the question). I think the question (and answers) are more useful this way, but feel free to rollback all the edits if you disagree.
  • Gino Mempin
    Gino Mempin about 2 years
    "then you can use a comma" It's called unpacking a list.
  • Timo
    Timo about 2 years
    Often you just want one part of the splitted string. Get it with 'match'.split('delim')[0] for the first one, etc.