python3设置编码为utf8,Python3:解码转换为字符串的UTF-8字节

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\xbceg\xc5\xbc\xc3\xb3\xc5\x82ka'

Now it's send as simple string (I get it as assertion from eval function). How the heck can I now get normal UTF-8 form of starting word? If there is some better compression than str(bytes(x)) then I would be glad to hear.

解决方案

If you want to encode and decode text, that's what the encode and decode methods are for:

>>> 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'

Also, notice that UTF-8 is already the default, so you can just do this:

>>> b = a.encode()

>>> c = b.decode()

The only reason you need to specify arguments is:

You need to use some other encoding instead of UTF-8,

You need to specify a specific error handler, like 'surrogatereplace' instead of 'strict', or

Your code has to run in Python 3.0-3.1 (which almost nobody used).

However, if you really want to, you can do what you were already doing; you just need to explicitly specify the encoding in the str call, just as you did in the bytes call:

>>> 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

Calling str on a bytes object without an encoding, as you were doing, doesn't decode it, and doesn't raise an exception like calling bytes on a str without an encoding, because the main job of str is to give you a string representation of the object—and the best string representation of a bytes object is that b'…'.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值