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

相關文章
相關標籤/搜索