推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
saximi
V2EX  ›  Python

请教一个 bytes 方法的问题

  •  
  •   saximi · Aug 15, 2017 · 3695 views
    This topic created in 3373 days ago, the information mentioned may be changed or developed.
    >>>S = 'eggs'
    >>>bytes(S, encoding='ascii') # str 转为 bytes
    b'eggs'

    请问上面的 bytes 命令调用中,encoding 参数表示什么含义,是说源字符串 S 的编码是 ascii,还是说转换后的目标 bytes 的编码是 ascii 呢?

    谢谢
    8 replies  •  2017-08-16 13:52:16 +08:00
    ethanlu
    ethanlu
    Aug 15, 2017 via Android
    1
    同是初学,参数就是 encoding 的方法,转换之后是 ASCII,前面多了个 b。
    Librazy
    Librazy
    Aug 16, 2017
    2
    https://docs.python.org/3.6/library/functions.html#func-bytes //Accordingly, constructor arguments are interpreted as for bytearray
    https://docs.python.org/3.6/library/stdtypes.html#bytearray
    encoding 参数指的是若 source 为 string 则用什么编码器编码为 bytes。

    @ethanlu 转换之后是 bytes,只是字面量以 ASCII 表示 (Only ASCII characters are permitted in bytes literals) 并且有前缀 b
    Librazy
    Librazy
    Aug 16, 2017
    3
    没写过(也暂时没学过 python,如果有错误请多多指教
    am241
    am241
    Aug 16, 2017 via Android
    4
    应该是目标编码,以目标编码的形式储存成 bytes
    timothyqiu
    timothyqiu
    Aug 16, 2017
    5
    encoding 指「使用何种规则编码」。

    字符串按照一定规则编码后,变成字节序列;字节序列按照一定规则解码后变成字符串。

    所以(从抽象角度讲)字符串是不存在「使用的是何种编码」一说的,只有字节序列才有使用何种编码的潜在属性。
    AZLisme
    AZLisme
    Aug 16, 2017
    6
    转换后的目标 bytes 的编码是 ascii
    ysc3839
    ysc3839
    Aug 16, 2017 via Android
    8
    encoding 代表编码,转换后的目标 bytes 的编码是 ascii。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1008 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 19:04 · PVG 03:04 · LAX 11:04 · JFK 14:04
    ♥ Do have faith in what you're doing.