为什么 Python 字符串无法正确比较?

Why does Python string fail to compare correctly?

我正在比较 Python 中的两个字符串。但是比较失败,发现变量firmwarehardware的值与字符串"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"returnTrue,应该是returningFalse

注: 我故意使用 create_string_buffer() 因为我将 gfirmwareghardware 传递给 C 函数。但是即使我没有将变量传递给 C 函数,也会出现此问题。

我查看了以下和其他帖子,但他们的问题是程序员在他们应该使用 ==.

时使用了关键字 is

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

Strange behavior when comparing unicode objects with string objects

您的 gfirmwareghardware 对象是大型字符缓冲区。当您使用 str(gfirmware,'utf-8') 将它们转换为字符串时,您会得到大字符串:

>>> len(str(gfirmware, 'utf-8'))
100

因为你还有所有的填充。

在转换为字符串之前,您可以在缓冲区上使用 value 属性:

>> firmware = str(gfirmware.value,'utf-8')
>> hardware = str(ghardware.value,'utf-8')
>> firmware != "firmware", hardware != "hardware"
(False, False)