Split a string by a delimiter in python
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Flying Over Ancient Lands
--
Chapters
00:00 Split A String By A Delimiter In Python
00:16 Accepted Answer Score 405
00:26 Answer 2 Score 4
00:44 Answer 3 Score 2
01:25 Answer 4 Score 2
01:51 Thank you
--
Full question
https://stackoverflow.com/questions/3475...
--
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
datewill have valueSa., 23. Märztimewill have value19:00event_namewill have valueKlavier + 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'