python 核心编程 第七章习题

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

转载于:https://www.cnblogs.com/muyiblog/p/6970780.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值