Python translator使用实例
1.string.maketrans设置字符串转换规则表(translation table)
代码如下:
allchars = string.maketrans('', '')#所有的字符串,即不替换字符串
aTob = string.maketrans('a','b')#将字符a转换为字符b
2.translate函数进行字符串的替换和删除,第一个参数是字符串转换规则表(translation table),第二个参数是要删除的字符串。比如,要将字符串s中的所有e替换为a,同时要删除所有的o 代码如下:
aTob = string.maketrans('e','a')
s = 'hello python'
print s.translate(aTob, 'o')
输出结果:
hall pythn
3.假如我们这样使用 代码如下:
allchars = string.maketrans('', '')
k = allchars.translate(allchars, 'a')
allchars表示所有的字符串,而k表示从所有的字符串中去除掉字符a,就是说所有的字符,除了a,因此,我们再调用如下方法时: 复制代码 代码如下:
s = 'abc'
print s.translate(allchars, k)
字面意思是,输出“字符串s中除去任何不是字符a的字符",即,只输出字符a,因此输出结果为:
a
4.现在,已经不难理解下面这个函数了 代码如下:
import string
def translator(frm='', to='', delete='', keep=None):
if len(to) == 1:
to = to * len(frm)
trans = string.maketrans(frm, to)
if keep is not None:
allchars = string.maketrans('', '')
delete = allchars.translate(allchars, keep.translate(allchars, delete))
def translate(s):
return s.translate(trans, delete)
return translate调用: 代码如下:
digits_only = translator(keep=string.digits)
print digits_only('Chris Perkins : 224-7992')
digits_to_hash = translator(frm=string.digits, to='#')
print digits_to_hash('Chris Perkins : 224-7992')
输出结果:
2247992
Chris Perkins : ###-####
(资源库 www.zyku.net)
您可能感兴趣的文章
- 04-24Python linecache.getline()读取文件中特定一行的脚本
- 04-24Python open读写文件实现脚本
- 04-24Python 过滤字符串的技巧,map与itertools.imap
- 04-24Python splitlines使用技巧
- 04-24Python struct.unpack
- 04-24Python 条件判断的缩写方法
- 04-24Python 大小写
- 04-24Python 除法小技巧
- 04-24Python 字符串中的字符倒转
- 04-24Python连接字符串(join %)
- 04-24Python strip lstrip rstrip使用方法
- 04-24Python ljust rjust center输出
- 04-24Python isinstance判断对象类型
- 04-24Python字符转换
- 04-24Python字符遍历
- 04-24Python交换变量
- 04-24Python备份Mysql脚本
- 04-24python备份文件的脚本
- 04-24python下如何让web元素的生成更简单的分析
- 04-24Python中的目录与文件判别代码
最近更新
阅读排行
猜你喜欢
- 02-21真我v11设置定时开关机教程
- 01-12华为音乐-华为音乐应用软件功能介绍
- 05-07华为mate30epro隐私相册设置教程
- 12-26phpyun人才网-phpyun人才网应用软件功
- 10-30免费自用图床,稳定极速图床
- 01-11途途课堂-途途课堂应用软件功能介绍
- 02-20centos普通用户设置sudo权限
- 02-14红米k30s选区区域截屏操作方法
- 12-24华为手机在哪查看重力感应
- 04-13魅族18pro取消锁屏壁纸设置方法