Wonderful String Translation Function in Python / Python神奇的字符串变换函数

本文深入探讨了Python中字符串转换的功能,特别是[string].translate([rule])函数的使用方法。该函数可以按照指定规则对字符串进行转换,规则字符串由256个字符组成,对应ASCII码表中的每个字符。文章还介绍了如何利用string库中的maketrans函数简化规则字符串的创建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值