最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python3?字符串str和bytes相互轉(zhuǎn)換

 更新時間:2022年03月23日 10:36:15   作者:Newjet666  
這篇文章主要介紹了python3?字符串str和bytes相互轉(zhuǎn)換,在文件傳輸過程中,通常使用bytes格式的數(shù)據(jù)流,而代碼中通常用str類型,因此str和bytes的相互轉(zhuǎn)換就尤為重要,下文詳細介紹需要的小伙伴可以參考一下

1.相關(guān)基礎(chǔ)

python3中有兩種字符串類型:strbytes

python編碼問題可以參考文章

strunicode編碼格式保存在內(nèi)存

所以使用時,不用管前面要不要加u

(python2中需要考慮,不加u的話,在一些場合會報錯)

#!/usr/bin/python3
str0="i am fine thank you"
?
print(type(str0))
print(str0)
?
str0=u"i am fine thank you"
?
print(type(str0))
print(str0)
?
# <class 'str'>
# i am fine thank you
# <class 'str'>
# i am fine thank you

定義byte類型時,在字符串前加b

#!/usr/bin/python3
str0=b"i am fine thank you"
?
print(type(str0))
print(str0)
?
# <class 'bytes'>
# b'i am fine thank you'

2.str和bytes相互轉(zhuǎn)換

在文件傳輸過程中,通常使用bytes格式的數(shù)據(jù)流,而代碼中通常用str類型,因此strbytes的相互轉(zhuǎn)換就尤為重要。

2.1 bytes->str

#!/usr/bin/python3
?
bytes_data = b'this is a message'
print(type(bytes_data))
print(bytes_data)
?
# 方法一:
str_data = str(bytes_data, encoding='utf-8')
print(type(str_data))
print(str_data)
?
# 方法二:
str_data = bytes_data.decode('utf-8')
print(type(str_data))
print(str_data)
?
# <class 'bytes'>
# b'this is a message'
# <class 'str'>
# this is a message
# <class 'str'>
# this is a message

2.2 str->bytes

#!/usr/bin/python3
?
str_data = 'this is a message'
print(type(str_data))
print(str_data)
# 方法一:
bytes_data = bytes(str_data, encoding='utf-8')
print(type(bytes_data))
print(bytes_data)
# 方法二:
bytes_data = str_data.encode('utf-8')
print(type(bytes_data))
print(bytes_data)
?
# <class 'str'>
# this is a message
# <class 'bytes'>
# b'this is a message'
# <class 'bytes'>
# b'this is a message'

到此這篇關(guān)于python3 字符串str和bytes相互轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)python3 str與bytes內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

宁晋县| 绥德县| 沁阳市| 望江县| 红桥区| 贵定县| 都匀市| 灵川县| 缙云县| 龙井市| 凉城县| 钟山县| 文成县| 武功县| 宜黄县| 拉萨市| 江山市| 抚松县| 河南省| 渭源县| 仪征市| 腾冲县| 分宜县| 左云县| 资中县| 阿合奇县| 中西区| 宜川县| 章丘市| 黄平县| 同德县| 彩票| 弋阳县| 遂宁市| 大埔县| 黎城县| 乌拉特后旗| 淅川县| 兴山县| 舟山市| 永安市|