比较 Python 中的两个变量
Comparing two variables in Python
我想在这里测试 a 和 b 是否相等。我不确定为什么输出会打印 'not equal',即使 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()
以将 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
并且知道它们具有相同类型的值。
文件内容总是在 strings/bytes 中返回,您需要相应地 convert/typecase。
'a'的值是整数75,而'b'的值是字符串“75”。如果计算相等,则结果将为假,因为它们不是同一类型。尝试将 b 转换为整数:
b = int(b)
我想在这里测试 a 和 b 是否相等。我不确定为什么输出会打印 'not equal',即使 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()
以将 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
并且知道它们具有相同类型的值。
文件内容总是在 strings/bytes 中返回,您需要相应地 convert/typecase。
'a'的值是整数75,而'b'的值是字符串“75”。如果计算相等,则结果将为假,因为它们不是同一类型。尝试将 b 转换为整数:
b = int(b)