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

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

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

    本文教程操作环境: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的相互转化,希望能对你有所帮助哦~

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

    相关文章推荐

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

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网