
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
string转为bytes
方法一:使用utf-8 的方式编码,转成 bytes
1 2 3 4 5 | >>> website_bytes_utf8 = website.encode(encoding= "utf-8" )
>>> type(website_bytes_utf8)
< class 'bytes' >
>>> website_bytes_utf8
b 'http://www.jb51.net/'
|
方法二:使用编码encode,转化成bytes
1 2 3 4 5 6 7 | str= "aabbcc"
bytes=str.encode( 'utf-8' )
print (str)
aabbcc
print (bytes)
b 'aabbcc'
|
bytes转为string
方法一:使用utf-8 的方式编码,转成 string
1 2 3 4 5 | >>> website_string = website_bytes_utf8.decode()
>>> type(website_string)
< class 'str' >
>>> website_string
'http://www.jb51.net/'
|
方法二:使用解码decode,转化成string
1 2 3 4 5 6 | bytes=b "aabbcc"
str=bytes.decode( 'utf-8' )
print (bytes)
b 'aabbcc'
print (str)
aabbcc
|
以上就是python中str和bytes的相互转化,希望能对你有所帮助哦~