python3中bytes与string的互相转换

首先来设置一个原始的字符串,

1 Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
2 Type "help", "copyright", "credits" or "license" for more information.
3 >>> website = 'http://www.cnblogs.com/txw1958/'
4 >>> type(website)
5 <class 'str'>
6 >>> website
7 'http://www.cnblogs.com/txw1958/'
8 >>>

按utf-8的方式编码,转成bytes

1 >>> website_bytes_utf8 = website.encode(encoding="utf-8")
2 >>> type(website_bytes_utf8)
3 <class 'bytes'>
4 >>> website_bytes_utf8
5 b'http://www.cnblogs.com/txw1958/'
6 >>>

按gb2312的方式编码,转成bytes

1 >>> website_bytes_gb2312 = website.encode(encoding="gb2312")
2 >>> type(website_bytes_gb2312)
3 <class 'bytes'>
4 >>> website_bytes_gb2312
5 b'http://www.cnblogs.com/txw1958/'
6 >>>

解码成string,默认不填

1 >>> website_string = website_bytes_utf8.decode()
2 >>> type(website_string)
3 <class 'str'>
4 >>> website_string
5 'http://www.cnblogs.com/txw1958/'
6 >>>
7 >>>

解码成string,使用gb2312的方式

1 >>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")
2 >>> type(website_string_gb2312)
3 <class 'str'>
4 >>> website_string_gb2312
5 'http://www.cnblogs.com/txw1958/'
6 >>>

 

posted on 2017-01-15 21:44  帅胡  阅读(349)  评论(0编辑  收藏  举报

导航