Python3 上 bytes 和 s

发布时间:2019-10-16 17:30:20编辑:auto阅读(2094)

    最近学 Python,在 coursera 上上 Programming for Everybody (Getting Started with Python) 这门课,就顺藤摸瓜地读了 python for informatics 这本书。书上用的 Python2 ,电脑装的3,有些地方不一样。例如 str 的 translate 方法在删除特定字符时死活不对。

    调出help查了一下。

    >>> help(str.translate)
    Help on method_descriptor:
    
    translate(...)
        S.translate(table) -> str
        
        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
    

    没有 deletechars 参数,难怪会有报错
    TypeError - Translate takes one argument.(2 given)
    而另一个数据类型bytes是有的。

    >>> help(bytes.translate)
    Help on method_descriptor:
    
    translate(...)
        translate(table, [deletechars])
        Return a copy with each character mapped by the given translation table.
        
          table
            Translation table, which must be a bytes object of length 256.
        
        All characters occurring in the optional argument deletechars are removed.
        The remaining characters are mapped through the given translation table.
    

    Python2 中有 str 和 Unicode 两种类型,而 Python3已经严格区分了 bytes 和 str 两种数据类型,str为原来的unicode,bytes代替了之前的str。

    在将字符串存入磁盘和从磁盘读取字符串的过程中,Python 自动地帮你完成了编码和解码的工作,你不需要关心它的过程,例如你能把一个中文赋值给字符串。而使用 bytes 类型,实质上是告诉 Python,不需要它帮你自动地完成编码和解码的工作,而是用户自己手动进行,并指定编码格式。

    现在你不能在需要 bytes 类型参数的时候使用 str 参数,反之亦然。str.translate(...)就不适合使用deletechar,因为一个Unicode字符经过编码后可能会和一些英文ACSII码混淆,而bytes中对单个字节操作不会有这种问题。

关键字