Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by a delimiter in python

People also ask

How do you split a text string in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string into two strings in Python?

Use Split () Function This function splits the string into smaller sections. This is the opposite of merging many strings into one. The split () function contains two parameters. In the first parameter, we pass the symbol that is used for the split.

Can I split a string by two delimiters Python?

Python has a built-in method you can apply to string, called . split() , which allows you to split a string by a certain delimiter.

How do you split a string in regex in Python?

Introduction to the Python regex split() function The built-in re module provides you with the split() function that splits a string by the matches of a regular expression. In this syntax: pattern is a regular expression whose matches will be used as separators for splitting. string is an input string to split.


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

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

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

When you have two or more (in the example below there're three) elements in the string, then you can use 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 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"