python - Convertir des octets en une chaîne

Mots clés : pythonstringpython-3.xpython

meilleur 5 Réponses python - Convertir des octets en une chaîne

vote vote

92

>>> b"abcde" b'abcde'  # utf-8 is used here because it is a very common encoding, but you # need to use the encoding your data is actually in. >>> b"abcde".decode("utf-8")  'abcde' 
vote vote

89

encoding = 'utf-8' 'hello'.decode(encoding) 
unicode('hello', encoding) 
encoding = 'utf-8' b'hello'.decode(encoding) 
str(b'hello', encoding) 
vote vote

73

>>> bytes_data = [112, 52, 52] >>> "".join(map(chr, bytes_data)) 'p44' 
vote vote

61

PY3K = sys.version_info >= (3, 0)  lines = [] for line in stream:     if not PY3K:         lines.append(line)     else:         lines.append(line.decode('cp437')) 
>>> b'\x00\x01\xffsd'.decode('utf-8') Traceback (most recent call last):   File "<stdin>", line 1, in <module> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid start byte 
PY3K = sys.version_info >= (3, 0)  lines = [] for line in stream:     if not PY3K:         lines.append(line)     else:         lines.append(line.decode('utf-8', 'backslashreplace')) 
# --- preparation  import codecs  def slashescape(err):     """ codecs error handler. err is UnicodeDecode instance. return     a tuple with a replacement for the unencodable part of the input     and a position where encoding should continue"""     #print err, dir(err), err.start, err.end, err.object[:err.start]     thebyte = err.object[err.start:err.end]     repl = u'\\x'+hex(ord(thebyte))[2:]     return (repl, err.end)  codecs.register_error('slashescape', slashescape)  # --- processing  stream = [b'\x80abc']  lines = [] for line in stream:     lines.append(line.decode('utf-8', 'slashescape')) 
vote vote

60

b'hello'.decode() 
b'hello'.decode(encoding="utf-8") 
b'hello'.decode(encoding) 

Questions similaires