Splitting Semicolon Separated String In Python
I want to split a semicolon separated string so that I can store each individual string to be used as text between XML tags using Python. The string value looks like this: 08-26-20
Solution 1:
Split returns a list as follows
>>> a="08-26-2009;08-27-2009;08-29-2009"
>>> a_split = a.split(';')
>>> a_split
['08-26-2009', '08-27-2009', '08-29-2009']
Solution 2:
child2.text, child3.text, child4.text = three_dates_text.split(';')
Solution 3:
When you have variables named child1, child2, child3, and child4, that is a code smell that hints that you that you should be using a list or some other kind of collection.
children = [ET.SubElement(tree, "sngdate")]
children += [ET.SubElement(children[0], "caldate%s" % i) for i in xrange(3)]
What had been four separate variables becomes a list with four elements. Now you can go about updating the dates in each of the items:
dates = "08-26-2009;08-27-2009;08-29-2009"
for i, d in enumerate(dates.split(";")):
children[i+1].date = d
You can adapt this to work for any number of items, even when you do not know the number of items in advance.
Post a Comment for "Splitting Semicolon Separated String In Python"