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

后端 未结 7 1940
慢半拍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:36

    The test if isinstance(data, bytes) or if type(data) == bytes, etc. doesn't work in Python 2, where a simple ASCII string passes the test of ! Because I use both Python 2 and Python 3, in order to overcome this I do the following check:

    if str(type(data)).find("bytes") != -1: print("It's ")
    

    It's a little ugly, but it does the job the question asks and it always works, in the simplest way.

提交回复
热议问题