python bytes和string相互轉換(46)

目錄

一.bytes和string區別

二.bytes轉string

string經過編碼encode轉化成bytes

三.string轉bytes

bytes經過解碼decode轉化成string

 

 


一.bytes和string區別

1.python bytes 也稱字節序列,並非字符。取值範圍 0 <= bytes <= 255,輸出的時候最前面會有字符b修飾;string 是python中字符串類型;

2.bytes主要是給在計算機看的,string主要是給人看的;

3.string經過編碼encode,轉化成二進制對象,給計算機識別;bytes經過解碼decode,轉化成string,讓我們看,但是注意反編碼的編碼規則是有範圍,\xc8就不是utf8識別的範圍;

if __name__ == "__main__":
    # 字節對象b
    b = b"shuopython.com"
    # 字符串對象s
    s = "shuopython.com"
    print(b)
    print(type(b))
    print(s)
    print(type(s))

輸出結果:

b'shuopython.com'
<class 'bytes'>
shuopython.com
<class 'str'>

 

二.bytes轉string

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.py
@Time:2020/2/26 21:25

@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""


if __name__ == "__main__":
    s = "shuopython.com"
    # 將字符串轉換爲字節對象
    b2 = bytes(s, encoding='utf8')  # 必須制定編碼格式
    # print(b2)

    # 字符串encode將獲得一個bytes對象
    b3 = str.encode(s)
    b4 = s.encode()
    print(b3)
    print(type(b3))
    print(b4)
    print(type(b4))

輸出結果:

b'shuopython.com'
<class 'bytes'>
b'shuopython.com'
<class 'bytes'>

 

 

三.string轉bytes

bytes經過解碼decode轉化成string

if __name__ == "__main__":
    # 字節對象b
    b = b"shuopython.com"
    print(b)
    b = bytes("猿說python", encoding='utf8')
    print(b)
    s2 = bytes.decode(b)
    s3 = b.decode()
    print(s2)
    print(s3)

輸出結果:

b'shuopython.com'
b'\xe7\x8c\xbf\xe8\xaf\xb4python'
猿說python
猿說python

 

猜你喜歡:

1.python bytes

2.python bytearray

3.python 深拷貝和淺拷貝

4.python 局部變量和全局變量

 

轉載請註明猿說Python » python bytes和string相互轉換

 

                                                                          技術交流、商務合作請直接聯繫博主

                                                                                     掃碼或搜索:猿說python

python教程公衆號

                                                                                         猿說python

                                                                               微信公衆號 掃一掃關注

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