解釋
??使用translate方法來對字串中的具體字符進行替換,如使用12345來替換aeiou,而使用translate方法需要先使用maketrans方法來構建替換表
??注:python2的maketrans方法需要匯入,而python3為內建,在python3中使用python2的語法來匯入會報錯ImportError: cannot import name ‘maketrans’
str.maketrans()
python檔案的解釋
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檔案的解釋
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分別替換為12345
trantab = str.maketrans("aeiou", "12345")
print ("EXAMPLE:aeiou".translate(trantab))
輸出為
EXAMPLE:12345
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/163557.html
標籤:其他
