Strings. Create a function that will return another string similar to the input string, but with its case inverted. For example, input of "Mr. Ed" will result in "mR. eD" as the output string.
1
#!/usr/bin/env python
2
#-*- coding:utf-8 -*-
3
#$Id: p0610.py 138 2010-05-21 09:10:35Z xylz $
4
5
'''
6
This is a 'python' study plan for xylz.
7
Copyright (C)2010 xylz (www.imxylz.info)
8
'''
9
10
import string
11
12
_letters = string.ascii_letters
13
_map = dict(zip(_letters,_letters[26:52]+_letters[0:26]))
14
15
def caseInverted(s):
16
if s is None or len(s) ==0: return s
17
r=[]
18
for c in s:
19
r.append(_map.get(c,c))
20
return ''.join(r)
21
22
if __name__ == '__main__':
23
'''
24
Create a function that will return another string similar to the input string, but with its case inverted. For example, input of "Mr. Ed" will result in "mR. eD" as the output string.
25
'''
26
print caseInverted('Mr.Liu')
27
第12行首先從string模塊里面加載所有字母的字符串,這個需要導(dǎo)入string模塊。
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

最重要的是第13行,通過兩個字符串(a-Z對應(yīng)A-Z+a-z)來構(gòu)造一個dic,這里用到了zip內(nèi)置函數(shù),同時通過dict包裝下,這樣就成了一個dict。
而在19行里面需要注意的是,對于那些不再dict里面的字符需要原樣返回,所以這里使用了get,如果直接使用下表操作[],會觸發(fā)一個異常。
使用dict的另一個好處就是速度可能會快點(diǎn),這個沒有測試,搞不好直接遍歷字符串找到對應(yīng)關(guān)系可能更快。