How do I not raise a Python exception when converting an integer-as-string to an int

六眼飞鱼酱① 提交于 2020-06-09 04:00:31

问题


I have some HTML I am trying to parse. There are cases where the html attributes alone are not going to help me identify the row type (header versus data). Fortunately, if my row is a data row then it should have some values that can be converted to integers. I have figured out how to convert the unicode to an integer for those cases that it is possible to make the conversion. I am struggling to write the logic to move past the cells that the conversion will not work because the cell has content that must be treated as text.

for example if rowColumn[1][3] can be converted to an integer I can do so by

int(rowColumn[1][3].replace(',','').strip('$'))

but I get an error if rowColumn[1][3] has text content.


回答1:


Have you looked at the try statement?

try:
    x = int(rowColumn[1][3].replace(',','').strip('$'))
except ValueError, e:
    x = None # rowColumn[1][3] was not an integer


来源:https://stackoverflow.com/questions/311963/how-do-i-not-raise-a-python-exception-when-converting-an-integer-as-string-to-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!