Python3: Decode UTF-8 bytes converted as string

后端 未结 2 754
迷失自我
迷失自我 2021-01-27 06:01

Suppose I have something like:

a = \"Gżegżółka\"
a = bytes(a, \'utf-8\')
a = str(a)

which returns string in form:

b\'G\\xc5\\xb         


        
2条回答
  •  旧巷少年郎
    2021-01-27 06:41

    I found it. The simplest way to convert string representation of bytes to bytes again is through the eval statement:

    a = "Gżegżółka"
    a = bytes(a, 'utf-8')
    a = str(a) #this is the input we deal with
    
    a = eval(a) #that's how we transform a into bytes
    a = str(a, 'utf-8') #...and now we convert it into string
    
    print(a)
    

提交回复
热议问题