zoukankan      html  css  js  c++  java
  • 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 >>>
  • 相关阅读:
    下雪诗
    华视身份证阅读器100UC HTTP模式二次开发
    C# Action 和 Func 区别
    网站部署——文件系统
    前端-JavaScript DOM和BOM
    IO多路复用
    python-协程
    python-线程
    python-进程
    计算机与操作系统简介
  • 原文地址:https://www.cnblogs.com/hushaojun/p/6287970.html
Copyright © 2011-2022 走看看