您的位置:首页 > 编程语言 > Python开发

python 核心编程 第七章习题

2017-06-09 10:35 176 查看
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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: