str.translate

简介:
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.

translate() 方法根据参数table给出的表(包含 256 个字符)转换字符串的字符,要过滤掉的字符放到 deletechars 参数中。

语法

translate()方法语法:

str.translate(table)
bytes.translate(table[, delete])    
bytearray.translate(table[, delete]) 

参数

  • table -- 翻译表,翻译表是通过 maketrans() 方法转换而来。
  • deletechars -- 字符串中要过滤的字符列表。

返回值

返回翻译后的字符串,若给出了 delete 参数,则将原来的bytes中的属于delete的字符删除,剩下的字符要按照table中给出的映射来进行映射 。

实例

以下实例展示了 translate() 函数的使用方法:

实例(Python 3.0+)

#!/usr/bin/python3 intab = " aeiou " outtab = " 12345 " trantab = str . maketrans ( intab , outtab ) # 制作翻译表 str = " this is string example....wow!!! " print ( str . translate ( trantab ) )

以上实例输出结果如下:

th3s 3s str3ng 2x1mpl2....w4w!!!

以下实例演示如何过滤掉的字符 o:

实例(Python 3.0+)

#!/usr/bin/python # 制作翻译表 bytes_tabtrans = bytes . maketrans ( b ' abcdefghijklmnopqrstuvwxyz ' , b ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ) # 转换为大写,并删除字母o print ( b ' runoob ' . translate ( bytes_tabtrans , b ' o ' ) )

以上实例输出结果:

b'RUNB'

目录
相关文章
|
4月前
|
编解码 测试技术 Python
【Python】已解决:UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not i
【Python】已解决:UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not i
775 1
|
编译器 Python
ValueError matplotlib display text must have all code points 128 or use Unicode strings
ValueError matplotlib display text must have all code points 128 or use Unicode strings
236 0
|
存储
TypeError: can only concatenate str (not “int“) to str
TypeError: can only concatenate str (not “int“) to str
384 0
TypeError: can only concatenate str (not “int“) to str
|
编解码
UnicodeEncodeError: 'latin-1' codec can't encode characters in position报错问题
UnicodeEncodeError: 'latin-1' codec can't encode characters in position报错问题
1197 1
|
JSON 数据格式 Python
python编程:json indent can't multiply sequence by non-int of type 'str'
python编程:json indent can't multiply sequence by non-int of type 'str'
176 0
(case when length(p.name)>25 then concat(substring(p.name,1,12),'...') else p.name end) as projectName
SELECT DISTINCT pw.project_id as projectId , (case when length(p.name)>25 then concat(substring(p.
1078 0