Wonderful String Translation Function in Python / Python神奇的字符串变换函数
来源:互联网 发布:一带一路的进展 知乎 编辑:程序博客网 时间:2024/05/08 18:12
So wonderful is the translation function in python, which seems to be deliberately designed for ascii encoding/decoding games...
the function of [string].translate([rule]) is translating the [string] into a certain string following the given [rule].
The [rule] is a string conprising exactly 256 characters indicating the corresponding objective character for each origin character ranged 0..255.
e.g. a rule string r, within values of r[65]='A', r[66]='2', etc., means the character of ascii 65 ('a'), should be converted into 'A', and the one of ascii 66('b') should be converted into '2';
You may think it boring to make up such a string artificially, for programmers are required to provide not only the mapping rule for the characters we want to translate but also the ones we don't care. It's especially dull to type in the invisible characters for the 256-chars-long string.
There's a function in string library helps you do this: string.maketrans([origin], [object])(Before using it you must import string first)
For example, if you want to translate all 'a's in a string to 'A' and all 'd's to '4' remaining all other characters unchanging, the rule_string = string.maketrans("da", "4A").
A complete example for the two functions' usage, it shift all the lowercase letters by 2 chars('a'->'c', 'b'->'d',..):
import string
a = "GlgkNgw qywq qrpgle.rpylqjyrc() gq y sqcdsj rmmj."
trans = string.maketrans("abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab")
print a.translate(trans)
- Wonderful String Translation Function in Python / Python神奇的字符串变换函数
- Python-字符串操作方法(Python-String-Function)
- Redis in Python: 字符串(String)
- python内建函数(build-in function)
- Python内置函数(built-in function)
- python 字符串string 处理函数
- Python-String-Function
- Python-String-Function
- python 中神奇的函数参数传递
- 【Python 笔记】神奇的匿名函数
- function definition in python
- nested function in python
- Sorting function in Python
- Linux 内核可用的字符串分割函数 strsep (String Split Function strsep in Linux Kernel)
- python的【字符串string】:运算符、内建函数
- Python的字符串操作string
- python的字符串函数
- 神奇的getattr - Python
- C#.NET中App_Code,App_Data等文件夹的作用
- dwr配置篇web.xml
- SCJP考试第二套2
- 软件开发项目范围、成本管理问题分析
- dwr简明配置备忘
- Wonderful String Translation Function in Python / Python神奇的字符串变换函数
- SCJP考试第二套3
- 专家看台:柯莱特CTO谈企业选择CRM的六大目标
- dwr.xml详解
- 使用 Split 方法分析字符串
- RichEdit保存为(*.txt)(*.doc)
- 310-025第二套3续
- 把DWR的配置写到Spring的配置文件里
- Strange error occured while accessing FDTY