python字符集轉換

1、python3 encode和decode:
  •     # --*-- coding:utf8 --*--
    • 在python文件的開頭,告知編譯器使用哪一種編碼格式來解釋文件;
  • encode() 和 decode()
    • 字符串 <=> 字節碼, 編碼和解碼就是在字符串和字節碼之間進行轉換;
    • encode() 文件編碼格式,默認爲utf8,也可以指定其他格式encode("gbk")
    • decode() 文件解碼格式,默認utf8, 也可以指定解碼格式decode("gbk")
  • python3中,取消了unicode類型,代替它的是使用unicode的字符串類型str
  • python3中,對文本和二進制數據做了更清晰的區分,不再對bytes字串進行自動編碼。文本總是unicode,由str表示,二進制數據由bytes表示。
  • python3中,不同字符集之間轉換,都要先轉換成unicode。
# --*-- coding:utf8 --*--

str = "你好"
print(type(str))

# 字符串str,由unicode轉換成gb2312
gb_str = str.encode("gb2312")
print(type(gb_str))

#字符串gb_str 直接轉成utf-8
"""
utf_str = gb_str.encode("utf8")
"""

# 不同字符集之間不能直接轉換,需要先解碼轉成unicode
unicode_str = gb_str.decode("gb2312")
print(type(unicode_str))
utf_str = unicode_str.encode("utf8")
print(type(utf_str))
print("============================")

# utf8 不能直接轉成其他格式,需要解碼爲unicode
unicode_str = utf_str.decode("utf8")
print(type(unicode_str))
gb_str = unicode_str.encode("gb2312")
print(type(utf_str))

運行結果:

<class 'str'>
<class 'bytes'>
<class 'str'>
<class 'bytes'>
============================
<class 'str'>
<class 'bytes'>

Process finished with exit code 0

2、python中Socket:

  • 套接字之間發送消息方法中,發送的數據爲bytes類型,需要進行字符集轉換。

3、python中 u、r、 b:

  • r: 非轉義的原始字符串,取消字符串中轉義字符的效果,不進行轉義 '\';
  • u: 表示unicode字符串,在python3中字符串就是unicode編碼,但還是建議中文前添加u"你好"
  • b:把字符串轉成bytes,但是僅限於ASCII內包含的,否則會報錯:SyntaxError: bytes can only contain ASCII literal characters。 通過b轉成bytes的字節,可以通過解碼轉換成字符串unicode

# --*-- coding:utf8 --*--

b_str = b"hello world"
print(type(b_str))

# 使用utf8 解碼爲字符串unicode
unicode_str = b_str.decode("utf8")
print(type(unicode_str))

b_str = b"hello world"
print(type(b_str))

# 使用gb2312 解碼爲字符串unicode
unicode_str = b_str.decode("gb2312")
print(type(unicode_str))

Result:

<class 'bytes'>
<class 'str'>
=========================
<class 'bytes'>
<class 'str'>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章