Python3 上 bytes 和 str

本文对比了Python2与Python3中str.translate方法的区别,详细解释了Python3中该方法的具体用法,包括如何通过翻译表实现字符替换及删除,并探讨了Unicode与ASCII字符处理上的差异。

最近学 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中对单个字节操作不会有这种问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值