码迷,mamicode.com
首页 > 编程语言 > 详细

python 核心编程 第七章习题

时间:2017-06-09 11:12:14      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:核心   tput   zip   test   基本   abc   index   nod   string   

7-9. 翻译
(a) 编写一个字符翻译程序(功能类似于Unix 中的tr 命令)。我们将这个函数叫做tr(),它有
三个字符串做参数: 源字符串、目的字符串、基本字符串,语法定义如下:
def tr(srcstr, dststr, string)
srcstr 的内容是你打算“翻译”的字符集合,dsrstr 是翻译后得到的字符集合,而string 是
你打算进行翻译操作的字符串。举例来说,如果srcstr == ‘abc‘, dststr == ‘mno‘, string ==
‘abcdef‘, 那么tr()的输出将是‘mnodef‘. 注意这里len(srcstr) == len(dststr).
在这个练习里,你可以使用内建函数chr() 和 ord(), 但它们并不一定是解决这个问题所必不
可少的函数。

 

def test79(strlist,srcstr = ‘abc‘,dststr = ‘mno‘):    
    sl = [] 
d = dict(zip(srcstr,dststr))
l = len(srcstr)
while not (strlist.find(srcstr) == -1):
#find place then replace it
index = strlist.index(srcstr)
sl = list(strlist)
for i in range(l):
sl[index + i] = d[strlist[index + i]]
strlist = ‘‘.join(sl)
print strlist

if __name__ == "__main__":
    test79("abccncabcdfdfjsnc")

#output: mnocncmnodfdfjsnc

python 核心编程 第七章习题

标签:核心   tput   zip   test   基本   abc   index   nod   string   

原文地址:http://www.cnblogs.com/muyiblog/p/6970780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!