[Python]pythonchallenge第1关--20131117

pythonchallenge第1关:

http://www.pythonchallenge.com/pc/def/map.html

K-->M

O-->Q

E-->G

即将每个字母+2,那么下面那一大段看起来像乱码的东西按此规律转换应该就是答案了吧。

 1 #!usr/bin/python
 2 # Filename:pythonchallenge1.py
 3 
 4 inputs = raw_input()
 5 word = ''
 6 for char in inputs:
 7     if char == ' ':
 8         print word,
 9         word = ''
10     elif char.isalpha():
11         if char == 'y':
12             word += 'a'
13         elif char == 'z':
14             word += 'b'
15         else:
16             word += chr(ord(char) + 2)
17     else:
18         word += char
19 print word

输入那段文字得到转换结果:

i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url.

将url中的map-->ocr,进入第二关。

 

---------------------------------------------再来看看上文提到的string.maketrans()是什么---------------------------------------------------------

官方文档说明:

static str.maketrans(from, to)

This static method returns a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

str.translate(table[,deletechars])

Return a copy of the s where all characters have been mapped through the map which must be a dictionary of Unicode ordinals (integers) to Unicode ordinals, strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.

简单来说就是maketrans()将from中的字符一一对应为to中的字符(因此from和to必须等长),并返回一个供translate使用的映射表table。而translate将移除字符串str中deletechars包含的字符,并将剩下的字符按照table中的映射关系进行一一映射。

尝试使用上述两个函数解决这一关的题目:

#!usr/bin/python
# Filename:pythonchallenge1.py

import string

inputs = raw_input()
table = string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',\
                         'cdefghijklmnopqrstuvwxyzabCDEFGHIJKLMNOPQRSTUVWXYZAB')
print inputs.translate(table)

输出:

i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url.

逻辑更简单,代码更简单,果然是神奇的python!

转载于:https://www.cnblogs.com/bluevoid7/p/3427978.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值