是从字符串而不是整数转换的整数吗?

时间:2016-12-08 01:25:32

标签: python python-3.x

怎么来

int('1') != int()
True

我将字符串转换为int,但表达式显示为True。

对不起。

任何人都可以告诉我如何实现这一目标"如果这不是一个int,那么True"

5 个答案:

答案 0 :(得分:3)

正如上面提到的那样,int()返回0。 为了确定变量是否为整数,您必须使用type。 所以你可以通过调用

检查变量是否为int
type(int('1')) == int

将返回true。 如果您要检查变量是否不是int,只需取消上面的代码:

type(int('1')) != int

答案 1 :(得分:0)

>>> int()
0
>>> int('1')
1

int()返回0,因此表达式的计算结果为1 != 0,即为True。如果你的意思更像:

>>> isinstance(int('1'), int)
True
>>> type(int('1')) == type(int())
True

答案 2 :(得分:0)

默认int()为0

要检查您的价值,您可以使用您可以使用类型: type(int('1'))

答案 3 :(得分:0)

isinstance(int('1'), int)

type(int('1')) == type(int())

两者都返回true

参考这个帖子How to check if type of a variable is string?,我相信它是一回事。

答案 4 :(得分:0)

从你得到的结果让我们这样看。

函数int()对输入的值执行强制转换,在您的情况下为“1”。所以它只是说:

cast '1' to an integer --> int('1') which gives 1

cast 'nothing' --> int() which gives '0'

因此,当您提出的问题int('1') != int()转换为:

is the value of the cast int('1') different from the value of the cast int()

那么答案应该正确 true 这就是你所拥有的。但如果你问过:

are their values the same, i.e. int('1') == int()

那么答案就是 false

相关问题