简体   繁体   English

比较Python中的两个变量

[英]Comparing two variables in Python

I'm trying to test for equality of a and b here. 我正在这里测试a和b的相等性。 I'm not sure why the output prints 'not equal' even though both a and b equates to '75', which is the same value. 我不确定为什么即使a和b都等于“ 75”(相同的值),输出也输出“不等于”。

a = (len(products)) #products is a dictionary, its length is 75
b = (f.read()) #f is a txt file that contains only '75'

if(str(a) == str(b)):
    print ('equal')
else:
    print ('not equal')

Add an int() around the f.read() to typecast the str to an int . f.read() int()周围添加一个int()以将str类型转换为一个int

>>> b = f.read().strip() # call strip to remove unwanted whitespace chars
>>> type(b)
<type 'str'>
>>>
>>> type(int(b))
<type 'int'>
>>>
>>> b = int(b)

Now you can compare a and b with the knowledge that they'd have values of the same type. 现在,您可以将ab与具有相同类型值的知识进行比较。

File contents are always returned in strings/bytes, and you need to convert/typecase accordingly. 文件内容总是以字符串/字节返回,因此您需要相应地转换/键入大小写。

The value of 'a' is 75 the integer while the value of 'b' is "75" the string. “ a”的值为75的整数,而“ b”的值为“ 75”的字符串。 When calculated if equal the result will be false because they are not the same type. 当计算是否相等时,结果将为假,因为它们不是同一类型。 Try casting b to an integer with: 尝试使用以下方法将b强制转换为整数:

b = int(b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM