V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2017-08-15 22:42:58 +08:00 · 2274 次点击
    这是一个创建于 2439 天前的主题,其中的信息可能已经有所发展或是发生改变。
    >>>S = 'eggs'
    >>>bytes(S, encoding='ascii') # str 转为 bytes
    b'eggs'

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

    谢谢
    8 条回复    2017-08-16 13:52:16 +08:00
    ethanlu
        1
    ethanlu  
       2017-08-15 22:55:45 +08:00 via Android
    同是初学,参数就是 encoding 的方法,转换之后是 ASCII,前面多了个 b。
    Librazy
        2
    Librazy  
       2017-08-16 00:40:45 +08:00
    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  
       2017-08-16 00:44:58 +08:00
    没写过(也暂时没学过 python,如果有错误请多多指教
    am241
        4
    am241  
       2017-08-16 02:59:31 +08:00 via Android
    应该是目标编码,以目标编码的形式储存成 bytes
    timothyqiu
        5
    timothyqiu  
       2017-08-16 03:45:42 +08:00
    encoding 指「使用何种规则编码」。

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

    所以(从抽象角度讲)字符串是不存在「使用的是何种编码」一说的,只有字节序列才有使用何种编码的潜在属性。
    AZLisme
        6
    AZLisme  
       2017-08-16 09:49:03 +08:00
    转换后的目标 bytes 的编码是 ascii
    daya0576
        7
    daya0576  
       2017-08-16 13:16:39 +08:00
    ysc3839
        8
    ysc3839  
       2017-08-16 13:52:16 +08:00 via Android
    encoding 代表编码,转换后的目标 bytes 的编码是 ascii。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   908 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:05 · PVG 05:05 · LAX 14:05 · JFK 17:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.