【发布时间】:2019-07-31 00:40:55
【问题描述】:
我在 Python 中比较两个字符串。但是对比看不出变量firmware和hardware的值与字符串"firmware"和"hardware"是一样的。
gfirmware = create_string_buffer(str.encode("firmware"), 100)
ghardware = create_string_buffer(str.encode("hardware"), 100)
firmware = str(gfirmware,'utf-8')
hardware = str(ghardware,'utf-8')
print('firmware var = ' + firmware)
print('hardware var = ' + hardware)
print("\n")
print('firmware type = ' + str(type(firmware)))
print('hardware type = ' + str(type(hardware)))
print('"firmware" type = ' + str(type("firmware")))
print('"hardware" type = ' + str(type("hardware")))
print("Is it true? " + str(firmware != "firmware" and hardware != "hardware"))
输出:
firmware var = firmware
hardware var = hardware
firmware type = <class 'str'>
hardware type = <class 'str'>
"firmware" type = <class 'str'>
"hardware" type = <class 'str'>
Is it true? True
变量和字符串的值和类型相同,从输出中可以看出。
那么为什么比较firmware != "firmware" and hardware != "hardware"返回True,它应该返回False?
注意:
我故意使用create_string_buffer(),因为我将gfirmware 和ghardware 传递给C 函数。但即使我没有将变量传递给 C 函数,也会出现此问题。
我查看了以下帖子和其他帖子,但他们的问题是程序员在本应使用 == 时使用了关键字 is。
Why does comparing strings using either '==' or 'is' sometimes produce a different result?
python fails to compare strings
Strange behavior when comparing unicode objects with string objects
【问题讨论】:
标签: python-3.x string-comparison