Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串转换的整数不是整数吗?_Python_Python 3.x - Fatal编程技术网

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

Python 从字符串转换的整数不是整数吗?,python,python-3.x,Python,Python 3.x,为什么 int('1') != int() True 我将字符串转换为int,但表达式显示为True 对不起 有谁能告诉我如何实现“如果这不是一个int,那么是真的”因为int()是: >>> int() 0 当然,1永远不等于0 >>> type(int('1')) == int True >>> isinstance(int('1'), int) True int()计算结果为0 您的代码基本上是int('1')==0 这是Fals

为什么

int('1') != int()
True
我将字符串转换为int,但表达式显示为True

对不起

有谁能告诉我如何实现“如果这不是一个int,那么是真的”

因为
int()
是:

>>> int()
0
当然,
1
永远不等于
0

>>> type(int('1')) == int
True
>>> isinstance(int('1'), int)
True
int()
计算结果为
0

您的代码基本上是
int('1')==0


这是
False

您正在尝试检查一个数字是否与其类型相等(实际上并没有这样做)。事实并非如此。数字就是数字,类型就是类型。要检查类型,请使用
type()
isinstance()

>x=type(int('1'))
>>>y=isinstance(int('1'),int)
>>>x
>>>x==int
真的
>>>y
真的
int()
返回0,因此表达式的计算结果为
1!=0
这是正确的。如果你的意思更像:

>>> isinstance(int('1'), int)
True
>>> type(int('1')) == type(int())
True
默认值
int()
为0

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

两者都返回
true


参考这条线索,我相信是一样的。

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

函数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()
那么答案应该是正确的,这就是你所拥有的。但如果你问:

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

那么答案应该是false

正如许多人在上面提到的,
int()
返回一个0。 要确定变量是否为整数,必须使用
类型
。 因此,您可以通过调用

type(int('1')) == int
它将返回
true
。 如果要检查变量是否为int,只需将上述代码取反即可:

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

谢谢,我怎样才能达到“如果这不是一个整数,那么是真的”?只要否定这个条件。
is the value of the cast int('1') different from the value of the cast int()
are their values the same, i.e. int('1') == int()
type(int('1')) == int
type(int('1')) != int