The Python Oracle

Split a string by a delimiter in python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping

--

Chapters
00:00 Question
00:23 Accepted answer (Score 391)
00:39 Answer 2 (Score 4)
01:00 Answer 3 (Score 2)
01:42 Answer 4 (Score 2)
02:35 Thank you

--

Full question
https://stackoverflow.com/questions/3475...

Accepted answer links:
[str.split]: https://docs.python.org/3/library/stdtyp...

Answer 2 links:
[csv]: http://docs.python.org/library/csv.html

Answer 3 links:
[this answer]: https://stackoverflow.com/a/47903325/392...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #list #split

#avk47



ACCEPTED ANSWER

Score 405


Use the str.split method:

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



ANSWER 2

Score 4


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", "MATCHES __ STRING" ]

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



ANSWER 3

Score 2


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



ANSWER 4

Score 2


For Python 3.8, you actually don't need the get_text method, you can just go with ev.split("@"), as a matter of fact the get_text method is throwing an AttributeError. So if you have a string variable, for example:

filename = 'file/foo/bar/fox'

You can just split that into different variables with comas as suggested in the above comment but with a correction:

W, X, Y, Z = filename.split('_') 
W = 'file' 
X = 'foo'
Y = 'bar'
Z = 'fox'