一.前言
在講解 str / bytes /unicode區別之前首先要明白位元組和字符的區別,請參考:bytearray/bytes/string區別 中對位元組和字符有清晰的講解,最重要是明白:
字符str是給人看的,例如:文本保存的內容,用來操作的;
位元組bytes是給計算機看的,例如:二進制資料,給計算機傳輸或者保存的;
二.str/bytes/unicode區別
1.在python2.x版本中str/bytes/unicode區別
在python2.x版本中str跟bytes是等價的;值得注意的是:bytes跟unicode是等價的,詳情見下圖
s1 = u"Hello, World!" s2 = "Hello, World!" print(type(s1)) print(type(s2))
輸出:
<type 'unicode'> <type 'str'>
2.在python3.x版本中str/bytes/unicode區別
在python3.x版本中str跟unicode是等價的;值得注意的是:bytes跟unicode是不等價的,詳情見下圖

s1 = u"Hello, World!" s2 = "Hello, World!" print(type(s1)) print(type(s2))
輸出:
<class 'str'> <class 'str'>
三.string與bytes相互轉換
1.string經過編碼encode轉化成bytes
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:何以解憂 @Blog(個人博客地址): shuopython.com @WeChat Official Account(微信公眾號):猿說python @Github:www.github.com @File:python_bytes_string_4.py @Time:2020/3/4 10:25 @Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累! """ s = "shuopython.com" #將字串轉換為位元組物件 b2 = bytes(s,encoding='utf8') #必須制定編碼格式 # print(b2) #方法一:字串encode將獲得一個bytes物件 b3 = str.encode(s) #方法二:字串encode將獲得一個bytes物件 b4 = s.encode() print(b3) print(type(b3)) print(b4) print(type(b4))
輸出結果:
b'shuopython.com' <class 'bytes'> b'shuopython.com' <class 'bytes'>
2.bytes經過解碼decode轉化成string
# 位元組物件b2 # 如果含有中文,必須制定編碼格式,否則報錯TypeError: string argument without an encoding b2 = bytes("猿說python", encoding='utf8') # 方法二:bytes物件decode將獲得一個字串 s2 = bytes.decode(b2) # 方法二:bytes物件decode將獲得一個字串 s3 = b2.decode() print(s2) print(s3)
輸出結果:
猿說python
猿說python
猜你喜歡:
1.python bytearray/bytes/string區別
2.python bytes
3.python bytearray
4.python 深拷貝和淺拷貝
5.python 區域變數和全域變數
轉載請注明:猿說Python ? python python str/bytes/unicode區別詳解
技術交流、商務合作請直接聯系博主 掃碼或搜索:猿說python
猿說python
微信公眾號 掃一掃關注
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/181245.html
標籤:Python
