• 技术文章 >常见问题 >Python常见问题

    python中str和bytes如何相互转化?

    宋雪维宋雪维2021-02-20 09:04:42原创8922

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

    string转为bytes

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

    >>> website_bytes_utf8 = website.encode(encoding="utf-8")
    >>> type(website_bytes_utf8)
    <class 'bytes'>
    >>> 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)
    <class 'str'>
    >>> 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的相互转化,希望能对你有所帮助哦~

    专题推荐:pythonstr与bytes转化?
    品易云
    上一篇:python中vars函数是什么意思? 下一篇:python中如何使用break跳出for循环?

    相关文章推荐

    • python中如何用ljust()实现字符串左对齐?• python中dir函数如何使用?• 如何使用python中的help函数?• python中vars函数是什么意思?• python中bytearray函数的作用是什么?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网