Convert bytes to a string

后端 未结 19 2329
野性不改
野性不改 2020-11-21 04:45

I\'m using this code to get standard output from an external program:

>>> from subprocess import *
>>> command_stdout = Popen([\'ls\', \'-l         


        
19条回答
  •  醉梦人生
    2020-11-21 05:18

    For Python 3, this is a much safer and Pythonic approach to convert from byte to string:

    def byte_to_str(bytes_or_str):
        if isinstance(bytes_or_str, bytes): # Check if it's in bytes
            print(bytes_or_str.decode('utf-8'))
        else:
            print("Object not of byte type")
    
    byte_to_str(b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n')
    

    Output:

    total 0
    -rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
    -rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2
    

提交回复
热议问题