text str.maketrans和翻译的描述

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text str.maketrans和翻译的描述相关的知识,希望对你有一定的参考价值。

str.maketrans builds a translation table, which is a mapping of integers or characters to integers, strings, or None. Think of it like a dictionary. We go through the string to translate and replace everything that appears as a key in the mapping with whatever its value in the map is.

You can build a translation table with one, two, three arguments (I think this may be what's confusing you). With one argument:

str.maketrans({'a': 'b', 'c': None})
You give the function a mapping that follows the rules for translation tables and it returns an equivalent table for that mapping. Things that map to None are removed

With two arguments:

str.maketrans('abc', 'xyz')
You give it two strings. Each character in the first string is replaced by the character at that index in the second string. So 'a' maps to 'x', 'b' to 'y', and 'c' to 'z'.

The one you're using, with three arguments, works the same as two arguments, but has a third string.

str.maketrans('abc', 'xyz', 'hij')
This is the same as the two argument version, except that the characters from the third string are removed, as if they were mapped to None. So your table is saying "Don't replace anything, but remove the characters that show up in this string".

以上是关于text str.maketrans和翻译的描述的主要内容,如果未能解决你的问题,请参考以下文章

轻松python文本专题-maketrans和translate

maketrans translate

maketrans与translate函数

python内置string模块

python: 字符串按空格分成列表split与加密密码maketrans

镜像字符串