xylz,imxylz

关注后端架构、中间件、分布式和并发编程

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  111 随笔 :: 10 文章 :: 2680 评论 :: 0 Trackbacks

6-10.

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'''
 6This is a 'python' study plan for xylz.
 7Copyright (C)2010 xylz (www.imxylz.info)
 8'''
 9
10import string
11
12_letters = string.ascii_letters
13_map = dict(zip(_letters,_letters[26:52]+_letters[0:26]))
14
15def 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
22if __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模块里面加载所有字母的字符串,这个需要导入string模块。
最重要的是第13行,通过两个字符串(a-Z对应A-Z+a-z)来构造一个dic,这里用到了zip内置函数,同时通过dict包装下,这样就成了一个dict。
而在19行里面需要注意的是,对于那些不再dict里面的字符需要原样返回,所以这里使用了get,如果直接使用下表操作[],会触发一个异常。
使用dict的另一个好处就是速度可能会快点,这个没有测试,搞不好直接遍历字符串找到对应关系可能更快。


©2009-2014 IMXYLZ |求贤若渴
posted on 2010-05-21 17:14 imxylz 阅读(16656) 评论(0)  编辑  收藏 所属分类: Python

只有注册用户登录后才能发表评论。


网站导航:
 

©2009-2014 IMXYLZ