将整数字符串转换为int时,如何不引发Python异常 [英] How do I not raise a Python exception when converting an integer-as-string to an int

查看:228
本文介绍了将整数字符串转换为int时,如何不引发Python异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析一些HTML.在某些情况下,仅html属性无法帮助我识别行类型(标题与数据).幸运的是,如果我的行是数据行,那么它应该具有一些可以转换为整数的值.我已经弄清楚了在可能进行转换的情况下,如何将unicode转换为整数.我正在努力编写逻辑以使逻辑越过这些转换将无法进行的单元格,因为该单元格具有必须被视为文本的内容.

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.

例如,如果rowColumn [1] [3]可以转换为整数,我可以通过

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

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

但是如果rowColumn [1] [3]具有文本内容,我会报错.

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

推荐答案

您是否看过try语句?

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

这篇关于将整数字符串转换为int时,如何不引发Python异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆