【问题标题】:python retrieve integer value of tag with minidom [duplicate]python用minidom检索标签的整数值[重复]
【发布时间】:2014-07-26 03:17:58
【问题描述】:

我想恢复标签的整数值

from xml.dom import minidom

docXML = minidom.parse('/root/Desktop/doc.xml')

node = docXML.getElementsByTagName('span')[0]

value = node.firstChild.data 

     " return value is 5.22%"

str1 = value.split('%') 

    "return [u'\n5.22', u'\n']"

finalvalue = ''.join(str1) 

     "return 5.22"

但是如果我想转换这个字符串字符

convert = int(finalvalue)

我收到以下错误

"ValueError  invalid literal for int() with base 10: '5.22 ' "

当我使用 split 方法时,我得到以下结果:

[u'\n5.22', u'\n']

【问题讨论】:

    标签: python xml tags minidom


    【解决方案1】:

    使用strip() 在转换为整数之前从字符串中删除空格,并使用float(the_str) 将其转换为float。

    >>> num_str = '5.22 '
    >>> int(num_str)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '5.22 '
    >>> float(num_str.strip())
    5.22
    

    【讨论】:

    • 非常感谢兄弟,你是我的救星^^
    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2012-04-11
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多