python str/bytes/unicode區別詳解(49)

目錄

一.前言

二.str/bytes/unicode區別

1.在python2.x版本中str/bytes/unicode區別

2.在python3.x版本中str/bytes/unicode區別

三.string與bytes相互轉換

1.string經過編碼encode轉化成bytes

2.bytes經過解碼decode轉化成string

 


一.前言

在講解 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教程公衆號

                                                                                  猿說python

                                                                          微信公衆號 掃一掃關注

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