【问题标题】:Why does Python string fail to compare correctly?为什么 Python 字符串无法正确比较?
【发布时间】:2019-07-31 00:40:55
【问题描述】:

我在 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"返回True,它应该返回False

注意: 我故意使用create_string_buffer(),因为我将gfirmwareghardware 传递给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


    【解决方案1】:

    您的 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)
    

    【讨论】:

    • 我没有想到它也会比较填充。我的 C 程序员认为0 是字符串终止字符。
    • 啊..我认为这个 fn 只是一些用户定义的代码,没有任何与问题的联系,尽管它让我一秒钟想到...现在我看到这是 python lib/外函数
    • 是的 @Fred — print(str(gfirmware,'utf-8')) 向您展示看起来像一个不错的普通字符串并没有帮助。 print(repr(str(gfirmware,'utf-8'))) 将向您展示 repr 版本的所有填充荣耀。
    猜你喜欢
    • 2013-03-12
    • 2016-01-03
    • 2022-01-16
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多