一.前言 在講解 str / bytes /unicode區別之前首先要明白位元組和字元的區別,請參考:bytearray/bytes/string區別 中對位元組和字元有清晰的講解,最重要是明白: 字元str是給人看的,例如:文本保存的內容,用來操作的; 位元組bytes是給電腦看的,例如:二進位數據 ...
一.前言
在講解 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區別
轉載請註明:猿說Python » python python str/bytes/unicode區別詳解
技術交流、商務合作請直接聯繫博主 掃碼或搜索:猿說python 猿說python 微信公眾號 掃一掃關註