Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-2009;08-27-2009;08-29-2009

They are just dates stored as string values

I want to iterate through each value, store to a variable and call the variable into the following code at the end:

for element in iter:
    # Look for a tag called "Timeinfo"
    if element.tag == "timeinfo":
        tree = root.find(".//timeinfo")
        # Clear all tags below "timeinfo"
        tree.clear()
        element.append(ET.Element("mdattim"))
        child1 = ET.SubElement(tree, "sngdate")
        child2 = ET.SubElement(child1, "caldate1")
        child3 = ET.SubElement(child1, "caldate2")
        child4 = ET.SubElement(child1, "caldate3")
        child2.text = FIRST DATE VARIABLE GOES HERE
        child2.text = SECOND DATE VARIABLE GOES HERE
        child2.text = THIRD DATE VARIABLE GOES HERE

Any help is appreciated.

like image 813
Mike Avatar asked Aug 05 '11 20:08

Mike


People also ask

How do you split a string separated 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 to a list using a comma delimiter in Python?

Python split() method splits the string into a comma separated list. It separates string based on the separator delimiter. This method takes two parameters and both are optional.

How do you parse comma-separated Values in Python?

Use str. split() to convert a comma-separated string to a list. Call str. split(sep) with "," as sep to convert a comma-separated string into a list.

Can you split () by a newline Python?

split() method splits the string by new line character and returns a list of strings. The string can also contain \n characters in the string as shown below, instead of a multi-line string with triple quotes.


2 Answers

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']
like image 118
Paul Hildebrandt Avatar answered Oct 31 '22 10:10

Paul Hildebrandt


child2.text, child3.text, child4.text = three_dates_text.split(';')
like image 20
pyroscope Avatar answered Oct 31 '22 10:10

pyroscope