在 Python 2.x 中,是不是有办法检查字符串是不是可以转换为整数? [复制]

Posted

技术标签:

【中文标题】在 Python 2.x 中,是不是有办法检查字符串是不是可以转换为整数? [复制]【英文标题】:In Python 2.x, is there anyway to check if a string can be converted to an integer? [duplicate]在 Python 2.x 中,是否有办法检查字符串是否可以转换为整数? [复制] 【发布时间】:2014-07-09 09:26:06 【问题描述】:

我想要一个程序将用户输入转换为整数并仅在可能的情况下将其存储在列表中。如果输入不能转换为整数,程序应该继续并忽略输入。

【问题讨论】:

注意有1e+2等特殊情况可以转成int 【参考方案1】:

这里最好的方法是尝试转换它,如果转换失败则忽略错误。例如:

try:
    your_list.append(int(user_input))
except ValueError:
    pass

【讨论】:

以上是关于在 Python 2.x 中,是不是有办法检查字符串是不是可以转换为整数? [复制]的主要内容,如果未能解决你的问题,请参考以下文章