What is the proper way to determine if an object is a bytes-like object in Python?

后端 未结 7 1802
慢半拍i
慢半拍i 2021-01-30 09:40

I have code that expects str but will handle the case of being passed bytes in the following way:

if isinstance(data, bytes):
    data          


        
7条回答
  •  生来不讨喜
    2021-01-30 10:32

    It depends what you want to solve. If you want to have the same code that converts both cases to a string, you can simply convert the type to bytes first, and then decode. This way, it is a one-liner:

    #!python3
    
    b1 = b'123456'
    b2 = bytearray(b'123456')
    
    print(type(b1))
    print(type(b2))
    
    s1 = bytes(b1).decode('utf-8')
    s2 = bytes(b2).decode('utf-8')
    
    print(s1)
    print(s2)
    

    This way, the answer for you may be:

    data = bytes(data).decode()
    

    Anyway, I suggest to write 'utf-8' explicitly to the decode, if you do not care to spare few bytes. The reason is that the next time you or someone else will read the source code, the situation will be more apparent.

提交回复
热议问题