python中字符串(string)的translate()和maketrans()方法

解释

  使用translate方法来对字符串中的具体字符进行替换,如使用12345来替换aeiou。而使用translate方法须要先使用maketrans方法来构建替换表
  注:python2的maketrans方法须要导入,而python3为内建。在python3中使用python2的语法来导入会报错ImportError: cannot import name ‘maketrans’
python

str.maketrans()

python文档的解释app

Help on built-in function maketrans in str:

str.maketrans = maketrans(...)
    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.translate()

python文档的解释ui

Help on method_descriptor in str:

str.translate = 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.

例子

将aeiou分别替换为12345this

trantab = str.maketrans("aeiou", "12345")

print ("EXAMPLE:aeiou".translate(trantab))

输出为spa

EXAMPLE:12345code

相关文章
相关标签/搜索