Python3:解码转换为字符串的UTF-8字节

时间:2018-07-05 22:56:23

标签: python python-3.x utf-8 decode encode

假设我有类似的东西:

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

以以下形式返回字符串:

b'G\xc5\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka'

现在,它以简单的字符串形式发送(我从eval函数中通过断言获得它)。我现在怎么能正常获得起始词的UTF-8形式?如果压缩比str(bytes(x))好,那我会很高兴的。

2 个答案:

答案 0 :(得分:1)

如果您想对文本进行编码和解码,那就是encodedecode方法的用途:

With isum.workSheets("Orders")
    With .Range(.Cells(2, "X"), .Cells(.Rows.Count, "O").End(xlUp).Offset(0, 9))
        .Formula = "=weeknum(o2)"
        .NumberFormat = "0_)"
        .FormatConditions.Delete
        With .FormatConditions.Add(Type:=xlExpression, Formula1:="=x2<weeknum(today())")
            .NumberFormat = "L\at\e_)"
            'optionally apply a red fill color
            '.interior.color = vbred
        End With
    End With
End With

此外,请注意,UTF-8已经是默认设置,因此您可以执行以下操作:

>>> a = "Gżegżółka"
>>> b = a.encode('utf-8')
>>> b
b'G\xc5\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka'
>>> c = b.decode('utf-8')
>>> c
'Gżegżółka'

您需要指定参数的唯一原因是:

  • 您需要使用其他编码代替UTF-8,
  • 您需要指定特定的错误处理程序,例如>>> b = a.encode() >>> c = b.decode() 而不是'surrogatereplace',或者
  • 您的代码必须在Python 3.0-3.1(几乎没有人使用)中运行。

但是,如果您确实愿意,您可以做您已经在做的事情;您只需要在'strict'调用中明确指定编码,就像在str调用中一样:

bytes

像您所做的那样,在没有编码的情况下在>>> a = "Gżegżółka" >>> b = bytes(a, 'utf-8') >>> b b'G\xc5\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka' >>> c = str(b, 'utf-8') >>> c 对象上调用str不会对它进行解码,也不会像在{{ 1}}没有编码,因为bytes的主要工作是为您提供对象的字符串表示形式,而bytes对象的最佳字符串表示形式是str。 / p>

答案 1 :(得分:0)

我找到了。将字节的字符串表示形式再次转换为字节的最简单方法是通过eval语句:

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)