为什么 Python 字符串类型在断言中也等于字节?

Why Python string type is also equal to bytes in assertions?

我想知道为什么这些断言会通过

    token_generated = ".eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImRhdmlkLmJhcnJhdEBub3ZhcnRpcy5jb20iLCJleHBpcmF0aW9uIjoiMjAxOC0wMS0xMVQyMjowNTozMi44MjIwNDUifQ.jalHa2ZpnxH00v3tP6CKL3nUkiTMt4rsjo6P3DM32DA"


    self.assertTrue(type(token_generated) == str)
    self.assertTrue(type(token_generated) == bytes)

两个测试都通过了,但我不明白为什么我的令牌变量可以有两种类型,因为它应该只是一个字符串

因为当我打印 token_generated

的类型时
    print (type(token_generated))

我明白了:.<type 'str'>

假设您使用的是 Python 2,str- 和 bytes- 类型实际上是相同的

>>> bytes is str
True

因此它们也相等

如果您想知道 token 是否是有效的 utf8 字符串,您应该对其进行解码:

token = '\xff'
try:
    token.decode('utf8')
except UnicodeDecodeError:
    print "The bytes are just bytes, or maybe some other encoding"
else:
    print "The bytes are a utf8 string, hooray"