加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

【Python有坑系列】python中编码问题——unicode, gbk, utf8

发布时间:2020-12-17 01:24:49 所属栏目:Python 来源:网络整理
导读:p style="margin-left:10px;" 1.默认编码类型 p style="margin-left:10px;"? pre class="has" code class="language-python" import sys sys.getdefaultencoding() 'utf-8' python 3.4默认为utf-8编码,python 3.4默认为Ascii编码 2. Python3 中字符串的类型

<p style="margin-left:10px;">1.默认编码类型

<p style="margin-left:10px;">?

<pre class="has">
<code class="language-python">>>> import sys

sys.getdefaultencoding()
'utf-8'

python 3.4默认为utf-8编码,python 3.4默认为Ascii编码

2. Python3 中字符串的类型

bytearray([source[,?encoding[,?errors]]])

<p style="margin-left:10px;">Return a new array of bytes. The?<a href="http://www.cnblogs.com/itech/admin/EditPosts.aspx?postid=1997878#bytearray" rel="nofollow">bytearray?type is a mutable sequence of integers in the range 0 <= x < 256.?

bytes([source[,?errors]]])

<p style="margin-left:10px;">Return a new “bytes” object,which is an immutable sequence of integers in the range?0 <= x < 256.?<a href="http://www.cnblogs.com/itech/admin/EditPosts.aspx?postid=1997878#bytes" rel="nofollow">bytes?is an immutable version of?<a href="http://www.cnblogs.com/itech/admin/EditPosts.aspx?postid=1997878#bytearray" rel="nofollow">bytearray.

str([object[,?errors]]])

<p style="margin-left:10px;">Return a string version of an object. str默认为unicode的字符串。

<p style="margin-left:10px;">3.实例?

<p style="margin-left:10px;">?

<pre class="has">
<code class="language-python">>>> us = "中国"

bs = b'AAA'
bs2 = bytes('中国','gbk')
print(us + ':' + str(type(us)))
中国:<class 'str'>
print(bs) #b'AAA'
b'AAA'
print(bs2)
b'xd6xd0xb9xfa'
print(':' + str(type(bs2)))
:<class 'bytes'>
print(bs2.decode('gbk')) #中国
中国

三 总结

<p style="margin-left:10px;">1) Python 3会假定我们的源码 — 即.py文件 — 使用的是UTF-8编码方式。Python 2里,.py文件默认的编码方式为ASCII。可以使用# -- coding: windows-1252 --方式来改变文件的编码。如果py文件中包含中文的字符串,则需要制定为# -- coding: gbk --,貌似默认的utf8不够哦。

<p style="margin-left:10px;">2) python3中默认的str为unicode的,可以使用str.encode来转为bytes类型。

<p style="margin-left:10px;">3) python3的print函数只支持unicode的str,貌似没有对bytes的解码功能,所以对对不能解码的bytes不能正确输出。?

<p style="margin-left:10px;">4) str和bytes不能连接和比较。?

<p style="margin-left:10px;">5) codecs任然可以用来str和bytes间的转化。?

<p style="margin-left:10px;">6) 定义非ascii码的bytes时,必须使用如?bytes(<span style="color:#800000;">'<span style="color:#800000;">中国<span style="color:#800000;">',<span style="color:#800000;">'<span style="color:#800000;">gbk<span style="color:#800000;">')?来转码。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读