Python 中 str.maketrans 和 str.translate 的使用

Python 中 str.maketrans 和 str.translate 的使用



1. str.maketrans

首先查看一下 str.maketrans 的帮助文档:

>>> help(str.maketrans)
Help on built-in function maketrans:

maketrans(x, y=None, z=None, /)
    Return a translation table usable for str.translate().
    
    If there is only one argument, it must be a dictionary mapping Unicode
    ordinals (integers) or characters to Unicode ordinals, strings or None.
    Character keys will be then converted to ordinals.
    If there are two arguments, they must be strings of equal length, and
    in the resulting dictionary, each character in x will be mapped to the
    character at the same position in y. If there is a third argument, it
    must be a string, whose characters will be mapped to None in the result.

str.maketrans 返回一个可以用于 str.translate 函数中的翻译表。
它可以接收一个、两个和三个参数。

  • 接收一个参数时,必须是一个字典,该字典是从 Unicode 序数(整数)或者字符到 Unicode 序数、字符串或者 None 的映射。
  • 接收两个参数时,必须是两个长度相等的字符串,在结果字典中,x 中的字符会被映射到 y 中同位置上的字符。
  • 接收三个参数时,最后一个参数是一个字符串,在结果字典中它被映射到 None

下面试试这三种构建翻译表的方法:

>>> table1 = {ord('1'): ord('a'), ord('2'): ord('b')}
>>> table1
{49: 97, 50: 98}
>>> table2 = str.maketrans({'1': 'a', '2': 'b'})
>>> table2
{49: 'a', 50: 'b'}
>>> table3 = str.maketrans('12', 'ab')
>>> table3
{49: 97, 50: 98}
>>> table4 = str.maketrans('12', 'ab', '中文')
>>> table4
{49: 97, 50: 98, 20013: None, 25991: None}

2. str.translate

首先查看一下 str.translate 的帮助文档:

>>> help(str.translate)
Help on method_descriptor:

translate(self, table, /)
    Replace each character in the string using the given translation table.
    
      table
        Translation table, which must be a mapping of Unicode ordinals to
        Unicode ordinals, strings, or None.
    
    The table must implement lookup/indexing via __getitem__, for instance a
    dictionary or list.  If this operation raises LookupError, the character is
    left untouched.  Characters mapped to None are deleted.

str.translate(table) 函数使用 table 作为翻译表,对原字符串中的内容进行替换,而被映射为 None 的字符会被删除。
下面使用上一节生成的 4 张翻译表进行翻译:

>>> '123中文'.translate(table1)
'ab3中文'
>>> '123中文'.translate(table2)
'ab3中文'
>>> '123中文'.translate(table3)
'ab3中文'
>>> '123中文'.translate(table4)
'ab3'

完成于 2019.02.03

猜你喜欢

转载自blog.csdn.net/jpch89/article/details/86759980