推荐学习书目
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 · 3215 views
    This topic created in 3215 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
        1
    ethanlu  
       Aug 15, 2017 via Android
    同是初学,参数就是 encoding 的方法,转换之后是 ASCII,前面多了个 b。
    Librazy
        2
    Librazy  
       Aug 16, 2017
    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
        3
    Librazy  
       Aug 16, 2017
    没写过(也暂时没学过 python,如果有错误请多多指教
    am241
        4
    am241  
       Aug 16, 2017 via Android
    应该是目标编码,以目标编码的形式储存成 bytes
    timothyqiu
        5
    timothyqiu  
       Aug 16, 2017
    encoding 指「使用何种规则编码」。

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

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