Ik heb bijvoorbeeld een string als deze (retourwaarde van subprocess.check_output
):
>>> b'a string'
b'a string'
Wat ik er ook mee gedaan heb, er staat altijd de irritante b'
voor de string:
>>> print(b'a string')
b'a string'
>>> print(str(b'a string'))
b'a string'
Heeft iemand enig idee hoe je het als een normale string kunt gebruiken of om het om te zetten in een normale string?
Antwoord 1, autoriteit 100%
Decodeer het.
>>> b'a string'.decode('ascii')
'a string'
Om bytes uit een string te halen, moet je deze coderen.
>>> 'a string'.encode('ascii')
b'a string'
Antwoord 2, autoriteit 19%
Als het antwoord van falsetru niet werkte, kun je het ook proberen:
>>> b'a string'.decode('utf-8')
'a string'
Antwoord 3
Zie de officiële encode()
en decode()
documentatie van codecs
bibliotheek. utf-8
is de standaardcodering voor de functies, maar er zijn verschillende standaardcoderingen in Python 3, zoals latin_1
of utf_32
.