成都网站建设设计

将想法与焦点和您一起共享

创新互联Python教程:python中str和bytes如何相互转化?

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

创新互联专注于复兴企业网站建设,响应式网站设计,商城网站制作。复兴网站建设公司,为复兴等地区提供建站服务。全流程按需策划设计,专业设计,全程项目跟踪,创新互联专业和态度为您提供的服务

string转为bytes

方法一:使用utf-8 的方式编码,转成 bytes

>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)

>>> website_bytes_utf8
b'http://www.jb51.net/'

方法二:使用编码encode,转化成bytes

str="aabbcc"
bytes=str.encode('utf-8')
 
print(str)
aabbcc
print(bytes)
b'aabbcc'

bytes转为string

方法一:使用utf-8 的方式编码,转成 string

>>> website_string = website_bytes_utf8.decode()
>>> type(website_string)

>>> website_string
'http://www.jb51.net/'

方法二:使用解码decode,转化成string

bytes=b"aabbcc"
str=bytes.decode('utf-8')
print(bytes)
b'aabbcc'
print(str)
aabbcc

以上就是python中str和bytes的相互转化,希望能对你有所帮助哦~


本文题目:创新互联Python教程:python中str和bytes如何相互转化?
转载注明:https://chengdu.cdxwcx.cn/article/cdodghg.html