如何知道列表中的字符串何时不能转换为整数?

2024-04-25 08:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

这样,如果有一个字符串不能转换成整数,它将产生一个错误消息

示例:

List = ['1', '2', 'a', '4/2']
->produce error message

List2 = ['1', '2', '4/2']
->proceed to condition

Tags: to字符串消息示例message错误整数error
3条回答
for x in mylist:
    try:
        int(x)
    except:
        print("not possible to convert into int_variable")

有一个字符串函数叫做“isdigit”

print '4'.isdigit()
True

你知道什么时候某个东西不能被转换成整数,因为它会抛出一个^{}。你知道吗

>>> list1 = ['1', '2', 'a', '4/2']
>>> for x in list1:
...     try:
...         int(x)
...     except ValueError:
...         print "Can't convert '%s' to an int" % x
...
1
2
Can't convert 'a' to an int
Can't convert '4/2' to an int

注意,在这个代码块中,只有'1''2'被转换为整数。'a'显然是一个字符。'4/2'是由数字组成的字符串。它不是作为数学表达式计算的。做这样的事情需要更复杂的逻辑。你知道吗

try/except逻辑很简单—将项转换为整数。如果抛出一个ValueException失败,则不能成为整数。你知道吗

最后,其他几个答案有try/except块。但是,它们没有捕获特定的异常类型。这是错误的practice.捕获特定的异常。你知道吗

相关问题 更多 >

    热门问题