在Python中分割分号分隔的字符串
我想分割一个以分号分隔的字符串,以便我可以使用 Python 存储每个单独的字符串,以用作 XML 标记之间的文本。字符串值如下所示:
08-26-2009;08-27-2009;08-29-2009
它们只是存储为字符串值的日期
我想迭代每个值,存储到变量并在最后将变量调用到以下代码中:
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
感谢任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
split返回一个列表如下
Split returns a list as follows
当您有名为 child1、child2、child3 和 child4 的变量时,这是一种代码味道,暗示您应该使用列表或其他类型的集合。
原来的四个独立变量变成了一个包含四个元素的列表。现在您可以开始更新每个项目中的日期:
即使您事先不知道项目数量,您也可以对其进行调整以适用于任意数量的项目。
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.
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:
You can adapt this to work for any number of items, even when you do not know the number of items in advance.