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 閱讀(16689) 評論(0)  編輯  收藏 所屬分類: Python

          ©2009-2014 IMXYLZ
          主站蜘蛛池模板: 苏尼特左旗| 禄劝| 双鸭山市| 山丹县| 华宁县| 荆门市| 贵港市| 衢州市| 莱西市| 博白县| 长沙县| 武冈市| 皋兰县| 毕节市| 兴文县| 泸定县| 屯昌县| 凤山县| 富民县| 平果县| 陆良县| 萍乡市| 北辰区| 竹溪县| 藁城市| 治多县| 临邑县| 河西区| 惠州市| 旅游| 双牌县| 大埔区| 安丘市| 镇康县| 阳城县| 武强县| 卢氏县| 聂荣县| 年辖:市辖区| 夏津县| 平乐县|