字符串不仅支持所有通用序列操作,还实现了很多附件方法。
我会以『字符串方法』为标题,分几篇笔记逐一介绍这些方法。
我会在这仓库中持续更新笔记:https://github.com/orca-j35/python_notes
translate
🔨 str.translate(table)
Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via __getitem__()
, typically a mapping or sequence. When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return None
, to delete the character from the return string; or raise a LookupError
exception, to map the character to itself.
# 该方法会按照table将字符串中的字符映射为指定的字符或字符串
# 在table中需使用码点作为键或索引
>>> table = {ord('a'): '#', ord('b'): '$$'}
>>> 'abcdabcd'.translate(table)
'#$$cd#$$cd'
# 在table中值为None,将被删除
>>> table = {ord('a'): '#', ord('b'): '$$',ord('c'):None}
>>> 'abcdabcd'.translate(table)
'#$$d#$$d'
You can use str.maketrans()
to create a translation map from character-to-character mappings in different formats.
See also the codecs
module for a more flexible approach to custom character mappings.
如果想要了解更多自定义字符映射的方法,可以查看 codecs
模块。
maketrans
🔨 static str.maketrans(x[, y[, z]])
This static method returns a translation table usable for str.translate()
.
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None
. Character keys will then be 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()使用的table
# 如果使用单参数形式,则x必须是一个字典,
# 该字典的键是Unicode码点或单个字符;该字典的值是码点或字符串或None,
# 如果键是字符,str.maketrans最终也会将其转换为码点
>>> d={97:'!','b':'##','c':None} # a的码点是97
>>> str.maketrans(d)
{97: '!', 98: '##', 99: None}
>>> 'abc'.translate(str.maketrans(d))
'!##'
# 如果使用双参数形式,则x和y必须是长度相同的字符串,
# x中的字符被逐一用作table字典的键,y中的字符被逐一用作table字典的值
>>> str.maketrans('abc','!@#')
{97: 33, 98: 64, 99: 35}
>>> 'abc'.translate(str.maketrans('abc','!@#'))
'!@#'
# 如果使用三参数形式,x和y与双参数的含义与双参数形式相同;
# z必须是一个字符串,该字符串中的字符会被映射为None,值为None的字符将被删除
>>> str.maketrans('abc','!@#','cde')
{97: 33, 98: 64, 99: None, 100: None, 101: None}
>>> 'abcdefg'.translate(str.maketrans('abc','!@#','cde'))
'!@fg'
网友评论