[英]Comparing two variables in Python
我正在这里测试a和b的相等性。 我不确定为什么即使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')
在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)
现在,您可以将a
和b
与具有相同类型值的知识进行比较。
文件内容总是以字符串/字节返回,因此您需要相应地转换/键入大小写。
“ a”的值为75的整数,而“ b”的值为“ 75”的字符串。 当计算是否相等时,结果将为假,因为它们不是同一类型。 尝试使用以下方法将b强制转换为整数:
b = int(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.