python中string模块各属性以及函数的用法

原文链接:http://blog.chinaunix.net/uid-25992400-id-3283846.html

任何语言都离不开字符,那就会涉及对字符的操作,尤其是脚本语言更是频繁,不管是生产环境还是面试考验都要面对字符串的操作。

    python的字符串操作通过2部分的方法函数基本上就可以解决所有的字符串操作需求:
  • python的字符串属性函数
  • python的string模块
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1. 字符串属性函数  
     系统版本:CentOS release 6.2 (Final)2.6.32-220.el6.x86_64
     python版本:Python 2.6.6

字符串属性方法

字符串格式输出对齐

[python]  view plain copy print ?
  1. 1.>>> str='stRINg lEArn'  
  2.   
  3. 2.>>>  
  4.   
  5. 3.>>> str.center(20)      #生成20个字符长度,str排中间  
  6.   
  7. 4.'    stRINg lEArn    '  
  8.   
  9. 5.>>>   
  10.   
  11. 6.>>> str.ljust(20)       #str左对齐  
  12.   
  13. 7.'stRINg lEArn        '    
  14.   
  15. 8.>>>  
  16.   
  17. 9.>>> str.rjust(20)       #str右对齐  
  18.   
  19. 10.'        stRINg lEArn'  
  20.   
  21. 11.>>>   
  22.   
  23. 12.>>> str.zfill(20)       #str右对齐,左边填充0  
  24.   
  25. 13.'00000000stRINg lEArn'  


大小写转换

[python]  view plain copy print ?
  1. 1.>>> str='stRINg lEArn'   
  2.   
  3. 2.>>>   
  4.   
  5. 3.>>> str.upper() #转大写  
  6.   
  7. 4.'STRING LEARN'  
  8.   
  9. 5.>>>   
  10.   
  11. 6.>>> str.lower() #转小写  
  12.   
  13. 7.'string learn'  
  14.   
  15. 8.>>>   
  16.   
  17. 9.>>> str.capitalize() #字符串首为大写,其余小写  
  18.   
  19. 10.'String learn'  
  20.   
  21. 11.>>>   
  22.   
  23. 12.>>> str.swapcase() #大小写对换  
  24.   
  25. 13.'STrinG LeaRN'  
  26.   
  27. 14.>>>   
  28.   
  29. 15.>>> str.title() #以分隔符为标记,首字符为大写,其余为小写  
  30.   
  31. 16.'String Learn'  


字符串条件判断

 

[python]  view plain copy print ?
  1. 1.>>> str='0123'  
  2.   
  3. 2.>>> str.isalnum()  #是否全是字母和数字,并至少有一个字符    
  4. 3.True  
  5.   
  6. 4.>>> str.isdigit()   #是否全是数字,并至少有一个字符   
  7. 5.True  
  8.   
  9. 6.  
  10.   
  11. 7.>>> str='abcd'  
  12.   
  13. 8.>>> str.isalnum()  
  14.   
  15. 9.True  
  16.   
  17. 10.>>> str.isalpha()   #是否全是字母,并至少有一个字符  
  18. 11.True  
  19.   
  20. 12.>>> str.islower()   #是否全是小写,当全是小写和数字一起时候,也判断为True   
  21. 13.True  
  22.   
  23. 14.  
  24.   
  25. 15.>>> str='abcd0123'  
  26.   
  27. 16.>>> str.islower()   #同上  
  28.   
  29. 17.True  
  30.   
  31. 18.>>> str.isalnum()     
  32.   
  33. 19.True  
  34.   
  35. 20.  
  36.   
  37. 21.>>> str=' '  
  38.   
  39. 22.>>> str.isspace()    #是否全是空白字符,并至少有一个字符   
  40. 23.True  
  41.   
  42. 24.>>> str='ABC'  
  43.   
  44. 25.>>> str.isupper()    #是否全是大写,当全是大写和数字一起时候,也判断为True   
  45. 26.True  
  46.   
  47. 27.>>> str='Abb Acc'  
  48.   
  49. 28.>>> str.istitle()    #所有单词字首都是大写,标题  
  50. 29.True  
  51. 30.  
  52.   
  53. 31.>>> str='string learn'  
  54. 32.>>> str.startswith('str'#判断字符串以'str'开头  
  55. 33.True  
  56. 34.>>> str.endswith('arn')   #判读字符串以'arn'结尾  
  57. 35.True  


字符串搜索定位与替换

[python]  view plain copy print ?
  1. 1.>>> str='string lEARn'  
  2.   
  3. 2.>>>   
  4.   
  5. 3.>>> str.find('a')      #查找字符串,没有则返回-1,有则返回查到到第一个匹配的索引  
  6.   
  7. 4.-1  
  8.   
  9. 5.>>> str.find('n')  
  10.   
  11. 6.4  
  12.   
  13. 7.>>> str.rfind('n')     #同上,只是返回的索引是最后一次匹配的  
  14.   
  15. 8.11  
  16.   
  17. 9.>>>   
  18.   
  19. 10.>>> str.index('a')     #如果没有匹配则报错  
  20.   
  21. 11.Traceback (most recent call last):  
  22.   
  23. 12.  File "<stdin>", line 1in <module>  
  24.   
  25. 13.ValueError: substring not found  
  26.   
  27. 14.>>> str.index('n')     #同find类似,返回第一次匹配的索引值  
  28.   
  29. 15.4  
  30.   
  31. 16.>>> str.rindex('n')    #返回最后一次匹配的索引值  
  32.   
  33. 17.11  
  34.   
  35. 18.>>>  
  36.   
  37. 19.>>> str.count('a')     #字符串中匹配的次数  
  38.   
  39. 20.0  
  40.   
  41. 21.>>> str.count('n')     #同上  
  42.   
  43. 22.2  
  44.   
  45. 23.>>>  
  46.   
  47. 24.>>> str.replace('EAR','ear')  #匹配替换  
  48.   
  49. 25.'string learn'  
  50.   
  51. 26.>>> str.replace('n','N')  
  52.   
  53. 27.'striNg lEARN'  
  54.   
  55. 28.>>> str.replace('n','N',1)  
  56.   
  57. 29.'striNg lEARn'  
  58.   
  59. 30.>>>  
  60.   
  61. 31.>>>  
  62.   
  63. 32.>>> str.strip('n')   #删除字符串首尾匹配的字符,通常用于默认删除回车符  
  64.   
  65. 33.'string lEAR'  
  66.   
  67. 34.>>> str.lstrip('n')  #左匹配  
  68.   
  69. 35.'string lEARn'  
  70.   
  71. 36.>>> str.rstrip('n')  #右匹配  
  72.   
  73. 37.'string lEAR'  
  74.   
  75. 38.>>>  
  76.   
  77. 39.>>> str='   tab'  
  78.   
  79. 40.>>> str.expandtabs()  #把制表符转为空格  
  80.   
  81. 41.'      tab'  
  82.   
  83. 42.>>> str.expandtabs(2#指定空格数  
  84.   
  85. 43.' tab'  


 

字符串编码与解码

[python]  view plain copy print ?
  1. 1.>>> str='字符串学习'  
  2.   
  3. 2.>>> str  
  4.   
  5. 3.'xe5xadx97xe7xacxa6xe4xb8xb2xe5xadxa6xe4xb9xa0'  
  6.   
  7. 4.>>>   
  8.   
  9. 5.>>> str.decode('utf-8')               #解码过程,将utf-8解码为unicode  
  10.   
  11. 6.u'u5b57u7b26u4e32u5b66u4e60'  
  12.   
  13. 7.  
  14.   
  15. 8.>>> str.decode('utf-8').encode('gbk')  #编码过程,将unicode编码为gbk  
  16.   
  17. 9.'xd7xd6xb7xfbxb4xaexd1xa7xcfxb0'  
  18.   
  19. 10.>>> str.decode('utf-8').encode('utf-8')  #将unicode编码为utf-8  
  20.   
  21. 11.'xe5xadx97xe7xacxa6xe4xb8xb2xe5xadxa6xe4xb9xa0'  


字符串分割变换

[python]  view plain copy print ?
  1. 1.>>> str='Learn string'  
  2.   
  3. 2.>>> '-'.join(str)  
  4.   
  5. 3.'L-e-a-r-n- -s-t-r-i-n-g'  
  6.   
  7. 4.>>> l1=['Learn','string']  
  8.   
  9. 5.>>> '-'.join(l1)  
  10.   
  11. 6.'Learn-string'  
  12.   
  13. 7.>>>   
  14.   
  15. 8.>>> str.split('n')  
  16.   
  17. 9.['Lear'' stri''g']  
  18.   
  19. 10.>>> str.split('n',1)  
  20.   
  21. 11.['Lear'' string']  
  22.   
  23. 12.>>> str.rsplit('n',1)  
  24.   
  25. 13.['Learn stri''g']  
  26.   
  27. 14.>>>  
  28.   
  29. 15.>>> str.splitlines()  
  30.   
  31. 16.['Learn string']  
  32.   
  33. 17.>>>  
  34.   
  35. 18.>>> str.partition('n')  
  36.   
  37. 19.('Lear''n'' string')  
  38.   
  39. 20.>>> str.rpartition('n')  
  40.   
  41. 21.('Learn stri''n''g')  


string模块源代码

[python]  view plain copy print ?
  1. 1."""A collection of string operations (most are no longer used). 
  2.  
  3. 2. 
  4.  
  5. 3.Warning: most of the code you see here isn't normally used nowadays. 
  6.  
  7. 4.Beginning with Python 1.6, many of these functions are implemented as 
  8.  
  9. 5.methods on the standard string object. They used to be implemented by 
  10.  
  11. 6.a built-in module called strop, but strop is now obsolete itself. 
  12.  
  13. 7. 
  14.  
  15. 8.Public module variables: 
  16.  
  17. 9. 
  18.  
  19. 10.whitespace -- a string containing all characters considered whitespace 
  20.  
  21. 11.lowercase -- a string containing all characters considered lowercase letters 
  22.  
  23. 12.uppercase -- a string containing all characters considered uppercase letters 
  24.  
  25. 13.letters -- a string containing all characters considered letters 
  26.  
  27. 14.digits -- a string containing all characters considered decimal digits 
  28.  
  29. 15.hexdigits -- a string containing all characters considered hexadecimal digits 
  30.  
  31. 16.octdigits -- a string containing all characters considered octal digits 
  32.  
  33. 17.punctuation -- a string containing all characters considered punctuation 
  34.  
  35. 18.printable -- a string containing all characters considered printable 
  36.  
  37. 19. 
  38.  
  39. 20."""  
  40.   
  41. 21.  
  42.   
  43. 22.# Some strings for ctype-style character classification  
  44.   
  45. 23.whitespace = ' tnrvf'  
  46.   
  47. 24.lowercase = 'abcdefghijklmnopqrstuvwxyz'  
  48.   
  49. 25.uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  
  50.   
  51. 26.letters = lowercase + uppercase  
  52.   
  53. 27.ascii_lowercase = lowercase  
  54.   
  55. 28.ascii_uppercase = uppercase  
  56.   
  57. 29.ascii_letters = ascii_lowercase + ascii_uppercase  
  58.   
  59. 30.digits = '0123456789'  
  60.   
  61. 31.hexdigits = digits + 'abcdef' + 'ABCDEF'  
  62.   
  63. 32.octdigits = '01234567'  
  64.   
  65. 33.punctuation = """!"#$%&'()*+,-./:;<=>?@[]^_`{|}~"""  
  66.   
  67. 34.printable = digits + letters + punctuation + whitespace  
  68.   
  69. 35.  
  70.   
  71. 36.# Case conversion helpers  
  72.   
  73. 37.# Use str to convert Unicode literal in case of -U  
  74.   
  75. 38.l = map(chr, xrange(256))  
  76.   
  77. 39._idmap = str('').join(l)  
  78.   
  79. 40.del l  
  80.   
  81. 41.  
  82.   
  83. 42.# Functions which aren't available as string methods.  
  84.   
  85. 43.  
  86.   
  87. 44.# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".  
  88.   
  89. 45.def capwords(s, sep=None):  
  90.   
  91. 46.    """capwords(s [,sep]) -> string 
  92.  
  93. 47. 
  94.  
  95. 48.    Split the argument into words using split, capitalize each 
  96.  
  97. 49.    word using capitalize, and join the capitalized words using 
  98.  
  99. 50.    join. If the optional second argument sep is absent or None, 
  100.  
  101. 51.    runs of whitespace characters are replaced by a single space 
  102.  
  103. 52.    and leading and trailing whitespace are removed, otherwise 
  104.  
  105. 53.    sep is used to split and join the words. 
  106.  
  107. 54. 
  108.  
  109. 55.    """  
  110.   
  111. 56.    return (sep or ' ').join(x.capitalize() for x in s.split(sep))  
  112.   
  113. 57.  
  114.   
  115. 58.  
  116.   
  117. 59.# Construct a translation string  
  118.   
  119. 60._idmapL = None  
  120.   
  121. 61.def maketrans(fromstr, tostr):  
  122.   
  123. 62.    """maketrans(frm, to) -> string 
  124.  
  125. 63. 
  126.  
  127. 64.    Return a translation table (a string of 256 bytes long) 
  128.  
  129. 65.    suitable for use in string.translate. The strings frm and to 
  130.  
  131. 66.    must be of the same length. 
  132.  
  133. 67. 
  134.  
  135. 68.    """  
  136.   
  137. 69.    if len(fromstr) != len(tostr):  
  138.   
  139. 70.        raise ValueError, "maketrans arguments must have same length"  
  140.   
  141. 71.    global _idmapL  
  142.   
  143. 72.    if not _idmapL:  
  144.   
  145. 73.        _idmapL = list(_idmap)  
  146.   
  147. 74.    L = _idmapL[:]  
  148.   
  149. 75.    fromstr = map(ord, fromstr)  
  150.   
  151. 76.    for i in range(len(fromstr)):  
  152.   
  153. 77.        L[fromstr[i]] = tostr[i]  
  154.   
  155. 78.    return ''.join(L)  
  156.   
  157. 79.  
  158.   
  159. 80.  
  160.   
  161. 81.  
  162.   
  163. 82.####################################################################  
  164.   
  165. 83.import re as _re  
  166.   
  167. 84.  
  168.   
  169. 85.class _multimap:  
  170.   
  171. 86.    """Helper class for combining multiple mappings. 
  172.  
  173. 87. 
  174.  
  175. 88.    Used by .{safe_,}substitute() to combine the mapping and keyword 
  176.  
  177. 89.    arguments. 
  178.  
  179. 90.    """  
  180.   
  181. 91.    def __init__(self, primary, secondary):  
  182.   
  183. 92.        self._primary = primary  
  184.   
  185. 93.        self._secondary = secondary  
  186.   
  187. 94.  
  188.   
  189. 95.    def __getitem__(self, key):  
  190.   
  191. 96.        try:  
  192.   
  193. 97.            return self._primary[key]  
  194.   
  195. 98.        except KeyError:  
  196.   
  197. 99.            return self._secondary[key]  
  198.   
  199. 100.  
  200.   
  201. 101.  
  202.   
  203. 102.class _TemplateMetaclass(type):  
  204.   
  205. 103.    pattern = r""" 
  206.  
  207. 104.    %(delim)s(?: 
  208.  
  209. 105.      (?P<escaped>%(delim)s) | # Escape sequence of two delimiters 
  210.  
  211. 106.      (?P<named>%(id)s) | # delimiter and a Python identifier 
  212.  
  213. 107.      {(?P<braced>%(id)s)} | # delimiter and a braced identifier 
  214.  
  215. 108.      (?P<invalid>) # Other ill-formed delimiter exprs 
  216.  
  217. 109.    ) 
  218.  
  219. 110.    """  
  220.   
  221. 111.  
  222.   
  223. 112.    def __init__(cls, name, bases, dct):  
  224.   
  225. 113.        super(_TemplateMetaclass, cls).__init__(name, bases, dct)  
  226.   
  227. 114.        if 'pattern' in dct:  
  228.   
  229. 115.            pattern = cls.pattern  
  230.   
  231. 116.        else:  
  232.   
  233. 117.            pattern = _TemplateMetaclass.pattern % {  
  234.   
  235. 118.                'delim' : _re.escape(cls.delimiter),  
  236.   
  237. 119.                'id' : cls.idpattern,  
  238.   
  239. 120.                }  
  240.   
  241. 121.        cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)  
  242.   
  243. 122.  
  244.   
  245. 123.  
  246.   
  247. 124.class Template:  
  248.   
  249. 125.    """A string class for supporting $-substitutions."""  
  250.   
  251. 126.    __metaclass__ = _TemplateMetaclass  
  252.   
  253. 127.  
  254.   
  255. 128.    delimiter = '$'  
  256.   
  257. 129.    idpattern = r'[_a-z][_a-z0-9]*'  
  258.   
  259. 130.  
  260.   
  261. 131.    def __init__(self, template):  
  262.   
  263. 132.        self.template = template  
  264.   
  265. 133.  
  266.   
  267. 134.    # Search for $$, $identifier, ${identifier}, and any bare $'s  
  268.   
  269. 135.  
  270.   
  271. 136.    def _invalid(self, mo):  
  272.   
  273. 137.        i = mo.start('invalid')  
  274.   
  275. 138.        lines = self.template[:i].splitlines(True)  
  276.   
  277. 139.        if not lines:  
  278.   
  279. 140.            colno = 1  
  280.   
  281. 141.            lineno = 1  
  282.   
  283. 142.        else:  
  284.   
  285. 143.            colno = i - len(''.join(lines[:-1]))  
  286.   
  287. 144.            lineno = len(lines)  
  288.   
  289. 145.        raise ValueError('Invalid placeholder in string: line %d, col %d' %  
  290.   
  291. 146.                         (lineno, colno))  
  292.   
  293. 147.  
  294.   
  295. 148.    def substitute(self, *args, **kws):  
  296.   
  297. 149.        if len(args) > 1:  
  298.   
  299. 150.            raise TypeError('Too many positional arguments')  
  300.   
  301. 151.        if not args:  
  302.   
  303. 152.            mapping = kws  
  304.   
  305. 153.        elif kws:  
  306.   
  307. 154.            mapping = _multimap(kws, args[0])  
  308.   
  309. 155.        else:  
  310.   
  311. 156.            mapping = args[0]  
  312.   
  313. 157.        # Helper function for .sub()  
  314.   
  315. 158.        def convert(mo):  
  316.   
  317. 159.            # Check the most common path first.  
  318.   
  319. 160.            named = mo.group('named'or mo.group('braced')  
  320.   
  321. 161.            if named is not None:  
  322.   
  323. 162.                val = mapping[named]  
  324.   
  325. 163.                # We use this idiom instead of str() because the latter will  
  326.   
  327. 164.                # fail if val is a Unicode containing non-ASCII characters.  
  328.   
  329. 165.                return '%s' % (val,)  
  330.   
  331. 166.            if mo.group('escaped'is not None:  
  332.   
  333. 167.                return self.delimiter  
  334.   
  335. 168.            if mo.group('invalid'is not None:  
  336.   
  337. 169.                self._invalid(mo)  
  338.   
  339. 170.            raise ValueError('Unrecognized named group in pattern',  
  340.   
  341. 171.                             self.pattern)  
  342.   
  343. 172.        return self.pattern.sub(convert, self.template)  
  344.   
  345. 173.  
  346.   
  347. 174.    def safe_substitute(self, *args, **kws):  
  348.   
  349. 175.        if len(args) > 1:  
  350.   
  351. 176.            raise TypeError('Too many positional arguments')  
  352.   
  353. 177.        if not args:  
  354.   
  355. 178.            mapping = kws  
  356.   
  357. 179.        elif kws:  
  358.   
  359. 180.            mapping = _multimap(kws, args[0])  
  360.   
  361. 181.        else:  
  362.   
  363. 182.            mapping = args[0]  
  364.   
  365. 183.        # Helper function for .sub()  
  366.   
  367. 184.        def convert(mo):  
  368.   
  369. 185.            named = mo.group('named')  
  370.   
  371. 186.            if named is not None:  
  372.   
  373. 187.                try:  
  374.   
  375. 188.                    # We use this idiom instead of str() because the latter  
  376.   
  377. 189.                    # will fail if val is a Unicode containing non-ASCII  
  378.   
  379. 190.                    return '%s' % (mapping[named],)  
  380.   
  381. 191.                except KeyError:  
  382.   
  383. 192.                    return self.delimiter + named  
  384.   
  385. 193.            braced = mo.group('braced')  
  386.   
  387. 194.            if braced is not None:  
  388.   
  389. 195.                try:  
  390.   
  391. 196.                    return '%s' % (mapping[braced],)  
  392.   
  393. 197.                except KeyError:  
  394.   
  395. 198.                    return self.delimiter + '{' + braced + '}'  
  396.   
  397. 199.            if mo.group('escaped'is not None:  
  398.   
  399. 200.                return self.delimiter  
  400.   
  401. 201.            if mo.group('invalid'is not None:  
  402.   
  403. 202.                return self.delimiter  
  404.   
  405. 203.            raise ValueError('Unrecognized named group in pattern',  
  406.   
  407. 204.                             self.pattern)  
  408.   
  409. 205.        return self.pattern.sub(convert, self.template)  
  410.   
  411. 206.  
  412.   
  413. 207.  
  414.   
  415. 208.  
  416.   
  417. 209.####################################################################  
  418.   
  419. 210.# NOTE: Everything below here is deprecated. Use string methods instead.  
  420.   
  421. 211.# This stuff will go away in Python 3.0.  
  422.   
  423. 212.  
  424.   
  425. 213.# Backward compatible names for exceptions  
  426.   
  427. 214.index_error = ValueError  
  428.   
  429. 215.atoi_error = ValueError  
  430.   
  431. 216.atof_error = ValueError  
  432.   
  433. 217.atol_error = ValueError  
  434.   
  435. 218.  
  436.   
  437. 219.# convert UPPER CASE letters to lower case  
  438.   
  439. 220.def lower(s):  
  440.   
  441. 221.    """lower(s) -> string 
  442.  
  443. 222. 
  444.  
  445. 223.    Return a copy of the string s converted to lowercase. 
  446.  
  447. 224. 
  448.  
  449. 225.    """  
  450.   
  451. 226.    return s.lower()  
  452.   
  453. 227.  
  454.   
  455. 228.# Convert lower case letters to UPPER CASE  
  456.   
  457. 229.def upper(s):  
  458.   
  459. 230.    """upper(s) -> string 
  460.  
  461. 231. 
  462.  
  463. 232.    Return a copy of the string s converted to uppercase. 
  464.  
  465. 233. 
  466.  
  467. 234.    """  
  468.   
  469. 235.    return s.upper()  
  470.   
  471. 236.  
  472.   
  473. 237.# Swap lower case letters and UPPER CASE  
  474.   
  475. 238.def swapcase(s):  
  476.   
  477. 239.    """swapcase(s) -> string 
  478.  
  479. 240. 
  480.  
  481. 241.    Return a copy of the string s with upper case characters 
  482.  
  483. 242.    converted to lowercase and vice versa. 
  484.  
  485. 243. 
  486.  
  487. 244.    """  
  488.   
  489. 245.    return s.swapcase()  
  490.   
  491. 246.  
  492.   
  493. 247.# Strip leading and trailing tabs and spaces  
  494.   
  495. 248.def strip(s, chars=None):  
  496.   
  497. 249.    """strip(s [,chars]) -> string 
  498.  
  499. 250. 
  500.  
  501. 251.    Return a copy of the string s with leading and trailing 
  502.  
  503. 252.    whitespace removed. 
  504.  
  505. 253.    If chars is given and not None, remove characters in chars instead. 
  506.  
  507. 254.    If chars is unicode, S will be converted to unicode before stripping. 
  508.  
  509. 255. 
  510.  
  511. 256.    """  
  512.   
  513. 257.    return s.strip(chars)  
  514.   
  515. 258.  
  516.   
  517. 259.# Strip leading tabs and spaces  
  518.   
  519. 260.def lstrip(s, chars=None):  
  520.   
  521. 261.    """lstrip(s [,chars]) -> string 
  522.  
  523. 262. 
  524.  
  525. 263.    Return a copy of the string s with leading whitespace removed. 
  526.  
  527. 264.    If chars is given and not None, remove characters in chars instead. 
  528.  
  529. 265. 
  530.  
  531. 266.    """  
  532.   
  533. 267.    return s.lstrip(chars)  
  534.   
  535. 268.  
  536.   
  537. 269.# Strip trailing tabs and spaces  
  538.   
  539. 270.def rstrip(s, chars=None):  
  540.   
  541. 271.    """rstrip(s [,chars]) -> string 
  542.  
  543. 272. 
  544.  
  545. 273.    Return a copy of the string s with trailing whitespace removed. 
  546.  
  547. 274.    If chars is given and not None, remove characters in chars instead. 
  548.  
  549. 275. 
  550.  
  551. 276.    """  
  552.   
  553. 277.    return s.rstrip(chars)  
  554.   
  555. 278.  
  556.   
  557. 279.  
  558.   
  559. 280.# Split a string into a list of space/tab-separated words  
  560.   
  561. 281.def split(s, sep=None, maxsplit=-1):  
  562.   
  563. 282.    """split(s [,sep [,maxsplit]]) -> list of strings 
  564.  
  565. 283. 
  566.  
  567. 284.    Return a list of the words in the string s, using sep as the 
  568.  
  569. 285.    delimiter string. If maxsplit is given, splits at no more than 
  570.  
  571. 286.    maxsplit places (resulting in at most maxsplit+1 words). If sep 
  572.  
  573. 287.    is not specified or is None, any whitespace string is a separator. 
  574.  
  575. 288. 
  576.  
  577. 289.    (split and splitfields are synonymous) 
  578.  
  579. 290. 
  580.  
  581. 291.    """  
  582.   
  583. 292.    return s.split(sep, maxsplit)  
  584.   
  585. 293.splitfields = split  
  586.   
  587. 294.  
  588.   
  589. 295.# Split a string into a list of space/tab-separated words  
  590.   
  591. 296.def rsplit(s, sep=None, maxsplit=-1):  
  592.   
  593. 297.    """rsplit(s [,sep [,maxsplit]]) -> list of strings 
  594.  
  595. 298. 
  596.  
  597. 299.    Return a list of the words in the string s, using sep as the 
  598.  
  599. 300.    delimiter string, starting at the end of the string and working 
  600.  
  601. 301.    to the front. If maxsplit is given, at most maxsplit splits are 
  602.  
  603. 302.    done. If sep is not specified or is None, any whitespace string 
  604.  
  605. 303.    is a separator. 
  606.  
  607. 304.    """  
  608.   
  609. 305.    return s.rsplit(sep, maxsplit)  
  610.   
  611. 306.  
  612.   
  613. 307.# Join fields with optional separator  
  614.   
  615. 308.def join(words, sep = ' '):  
  616.   
  617. 309.    """join(list [,sep]) -> string 
  618.  
  619. 310. 
  620.  
  621. 311.    Return a string composed of the words in list, with 
  622.  
  623. 312.    intervening occurrences of sep. The default separator is a 
  624.  
  625. 313.    single space. 
  626.  
  627. 314. 
  628.  
  629. 315.    (joinfields and join are synonymous) 
  630.  
  631. 316. 
  632.  
  633. 317.    """  
  634.   
  635. 318.    return sep.join(words)  
  636.   
  637. 319.joinfields = join  
  638.   
  639. 320.  
  640.   
  641. 321.# Find substring, raise exception if not found  
  642.   
  643. 322.def index(s, *args):  
  644.   
  645. 323.    """index(s, sub [,start [,end]]) -> int 
  646.  
  647. 324. 
  648.  
  649. 325.    Like find but raises ValueError when the substring is not found. 
  650.  
  651. 326. 
  652.  
  653. 327.    """  
  654.   
  655. 328.    return s.index(*args)  
  656.   
  657. 329.  
  658.   
  659. 330.# Find last substring, raise exception if not found  
  660.   
  661. 331.def rindex(s, *args):  
  662.   
  663. 332.    """rindex(s, sub [,start [,end]]) -> int 
  664.  
  665. 333. 
  666.  
  667. 334.    Like rfind but raises ValueError when the substring is not found. 
  668.  
  669. 335. 
  670.  
  671. 336.    """  
  672.   
  673. 337.    return s.rindex(*args)  
  674.   
  675. 338.  
  676.   
  677. 339.# Count non-overlapping occurrences of substring  
  678.   
  679. 340.def count(s, *args):  
  680.   
  681. 341.    """count(s, sub[, start[,end]]) -> int 
  682.  
  683. 342. 
  684.  
  685. 343.    Return the number of occurrences of substring sub in string 
  686.  
  687. 344.    s[start:end]. Optional arguments start and end are 
  688.  
  689. 345.    interpreted as in slice notation. 
  690.  
  691. 346. 
  692.  
  693. 347.    """  
  694.   
  695. 348.    return s.count(*args)  
  696.   
  697. 349.  
  698.   
  699. 350.# Find substring, return -1 if not found  
  700.   
  701. 351.def find(s, *args):  
  702.   
  703. 352.    """find(s, sub [,start [,end]]) -> in 
  704.  
  705. 353. 
  706.  
  707. 354.    Return the lowest index in s where substring sub is found, 
  708.  
  709. 355.    such that sub is contained within s[start,end]. Optional 
  710.  
  711. 356.    arguments start and end are interpreted as in slice notation. 
  712.  
  713. 357. 
  714.  
  715. 358.    Return -1 on failure. 
  716.  
  717. 359. 
  718.  
  719. 360.    """  
  720.   
  721. 361.    return s.find(*args)  
  722.   
  723. 362.  
  724.   
  725. 363.# Find last substring, return -1 if not found  
  726.   
  727. 364.def rfind(s, *args):  
  728.   
  729. 365.    """rfind(s, sub [,start [,end]]) -> int 
  730.  
  731. 366. 
  732.  
  733. 367.    Return the highest index in s where substring sub is found, 
  734.  
  735. 368.    such that sub is contained within s[start,end]. Optional 
  736.  
  737. 369.    arguments start and end are interpreted as in slice notation. 
  738.  
  739. 370. 
  740.  
  741. 371.    Return -1 on failure. 
  742.  
  743. 372. 
  744.  
  745. 373.    """  
  746.   
  747. 374.    return s.rfind(*args)  
  748.   
  749. 375.  
  750.   
  751. 376.# for a bit of speed  
  752.   
  753. 377._float = float  
  754.   
  755. 378._int = int  
  756.   
  757. 379._long = long  
  758.   
  759. 380.  
  760.   
  761. 381.# Convert string to float  
  762.   
  763. 382.def atof(s):  
  764.   
  765. 383.    """atof(s) -> float 
  766.  
  767. 384. 
  768.  
  769. 385.    Return the floating point number represented by the string s. 
  770.  
  771. 386. 
  772.  
  773. 387.    """  
  774.   
  775. 388.    return _float(s)  
  776.   
  777. 389.  
  778.   
  779. 390.  
  780.   
  781. 391.# Convert string to integer  
  782.   
  783. 392.def atoi(s , base=10):  
  784.   
  785. 393.    """atoi(s [,base]) -> int 
  786.  
  787. 394. 
  788.  
  789. 395.    Return the integer represented by the string s in the given 
  790.  
  791. 396.    base, which defaults to 10. The string s must consist of one 
  792.  
  793. 397.    or more digits, possibly preceded by a sign. If base is 0, it 
  794.  
  795. 398.    is chosen from the leading characters of s, 0 for octal, 0x or 
  796.  
  797. 399.    0X for hexadecimal. If base is 16, a preceding 0x or 0X is 
  798.  
  799. 400.    accepted. 
  800.  
  801. 401. 
  802.  
  803. 402.    """  
  804.   
  805. 403.    return _int(s, base)  
  806.   
  807. 404.  
  808.   
  809. 405.  
  810.   
  811. 406.# Convert string to long integer  
  812.   
  813. 407.def atol(s, base=10):  
  814.   
  815. 408.    """atol(s [,base]) -> long 
  816.  
  817. 409. 
  818.  
  819. 410.    Return the long integer represented by the string s in the 
  820.  
  821. 411.    given base, which defaults to 10. The string s must consist 
  822.  
  823. 412.    of one or more digits, possibly preceded by a sign. If base 
  824.  
  825. 413.    is 0, it is chosen from the leading characters of s, 0 for 
  826.  
  827. 414.    octal, 0x or 0X for hexadecimal. If base is 16, a preceding 
  828.  
  829. 415.    0x or 0X is accepted. A trailing L or l is not accepted, 
  830.  
  831. 416.    unless base is 0. 
  832.  
  833. 417. 
  834.  
  835. 418.    """  
  836.   
  837. 419.    return _long(s, base)  
  838.   
  839. 420.  
  840.   
  841. 421.  
  842.   
  843. 422.# Left-justify a string  
  844.   
  845. 423.def ljust(s, width, *args):  
  846.   
  847. 424.    """ljust(s, width[, fillchar]) -> string 
  848.  
  849. 425. 
  850.  
  851. 426.    Return a left-justified version of s, in a field of the 
  852.  
  853. 427.    specified width, padded with spaces as needed. The string is 
  854.  
  855. 428.    never truncated. If specified the fillchar is used instead of spaces. 
  856.  
  857. 429. 
  858.  
  859. 430.    """  
  860.   
  861. 431.    return s.ljust(width, *args)  
  862.   
  863. 432.  
  864.   
  865. 433.# Right-justify a string  
  866.   
  867. 434.def rjust(s, width, *args):  
  868.   
  869. 435.    """rjust(s, width[, fillchar]) -> string 
  870.  
  871. 436. 
  872.  
  873. 437.    Return a right-justified version of s, in a field of the 
  874.  
  875. 438.    specified width, padded with spaces as needed. The string is 
  876.  
  877. 439.    never truncated. If specified the fillchar is used instead of spaces. 
  878.  
  879. 440. 
  880.  
  881. 441.    """  
  882.   
  883. 442.    return s.rjust(width, *args)  
  884.   
  885. 443.  
  886.   
  887. 444.# Center a string  
  888.   
  889. 445.def center(s, width, *args):  
  890.   
  891. 446.    """center(s, width[, fillchar]) -> string 
  892.  
  893. 447. 
  894.  
  895. 448.    Return a center version of s, in a field of the specified 
  896.  
  897. 449.    width. padded with spaces as needed. The string is never 
  898.  
  899. 450.    truncated. If specified the fillchar is used instead of spaces. 
  900.  
  901. 451. 
  902.  
  903. 452.    """  
  904.   
  905. 453.    return s.center(width, *args)  
  906.   
  907. 454.  
  908.   
  909. 455.# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'  
  910.   
  911. 456.# Decadent feature: the argument may be a string or a number  
  912.   
  913. 457.# (Use of this is deprecated; it should be a string as with ljust c.s.)  
  914.   
  915. 458.def zfill(x, width):  
  916.   
  917. 459.    """zfill(x, width) -> string 
  918.  
  919. 460. 
  920.  
  921. 461.    Pad a numeric string x with zeros on the left, to fill a field 
  922.  
  923. 462.    of the specified width. The string x is never truncated. 
  924.  
  925. 463. 
  926.  
  927. 464.    """  
  928.   
  929. 465.    if not isinstance(x, basestring):  
  930.   
  931. 466.        x = repr(x)  
  932.   
  933. 467.    return x.zfill(width)  
  934.   
  935. 468.  
  936.   
  937. 469.# Expand tabs in a string.  
  938.   
  939. 470.# Doesn't take non-printing chars into account, but does understand n.  
  940.   
  941. 471.def expandtabs(s, tabsize=8):  
  942.   
  943. 472.    """expandtabs(s [,tabsize]) -> string 
  944.  
  945. 473. 
  946.  
  947. 474.    Return a copy of the string s with all tab characters replaced 
  948.  
  949. 475.    by the appropriate number of spaces, depending on the current 
  950.  
  951. 476.    column, and the tabsize (default 8). 
  952.  
  953. 477. 
  954.  
  955. 478.    """  
  956.   
  957. 479.    return s.expandtabs(tabsize)  
  958.   
  959. 480.  
  960.   
  961. 481.# Character translation through look-up table.  
  962.   
  963. 482.def translate(s, table, deletions=""):  
  964.   
  965. 483.    """translate(s,table [,deletions]) -> string 
  966.  
  967. 484. 
  968.  
  969. 485.    Return a copy of the string s, where all characters occurring 
  970.  
  971. 486.    in the optional argument deletions are removed, and the 
  972.  
  973. 487.    remaining characters have been mapped through the given 
  974.  
  975. 488.    translation table, which must be a string of length 256. The 
  976.  
  977. 489.    deletions argument is not allowed for Unicode strings. 
  978.  
  979. 490. 
  980.  
  981. 491.    """  
  982.   
  983. 492.    if deletions or table is None:  
  984.   
  985. 493.        return s.translate(table, deletions)  
  986.   
  987. 494.    else:  
  988.   
  989. 495.        # Add s[:0] so that if s is Unicode and table is an 8-bit string,  
  990.   
  991. 496.        # table is converted to Unicode. This means that table *cannot*  
  992.   
  993. 497.        # be a dictionary -- for that feature, use u.translate() directly.  
  994.   
  995. 498.        return s.translate(table + s[:0])  
  996.   
  997. 499.  
  998.   
  999. 500.# Capitalize a string, e.g. "aBc dEf" -> "Abc def".  
  1000.   
  1001. 501.def capitalize(s):  
  1002.   
  1003. 502.    """capitalize(s) -> string 
  1004.  
  1005. 503. 
  1006.  
  1007. 504.    Return a copy of the string s with only its first character 
  1008.  
  1009. 505.    capitalized. 
  1010.  
  1011. 506. 
  1012.  
  1013. 507.    """  
  1014.   
  1015. 508.    return s.capitalize()  
  1016.   
  1017. 509.  
  1018.   
  1019. 510.# Substring replacement (global)  
  1020.   
  1021. 511.def replace(s, old, new, maxsplit=-1):  
  1022.   
  1023. 512.    """replace (str, old, new[, maxsplit]) -> string 
  1024.  
  1025. 513. 
  1026.  
  1027. 514.    Return a copy of string str with all occurrences of substring 
  1028.  
  1029. 515.    old replaced by new. If the optional argument maxsplit is 
  1030.  
  1031. 516.    given, only the first maxsplit occurrences are replaced. 
  1032.  
  1033. 517. 
  1034.  
  1035. 518.    """  
  1036.   
  1037. 519.    return s.replace(old, new, maxsplit)  
  1038.   
  1039. 520.  
  1040.   
  1041. 521.  
  1042.   
  1043. 522.# Try importing optional built-in module "strop" -- if it exists,  
  1044.   
  1045. 523.# it redefines some string operations that are 100-1000 times faster.  
  1046.   
  1047. 524.# It also defines values for whitespace, lowercase and uppercase  
  1048.   
  1049. 525.# that match <ctype.h>'s definitions.  
  1050.   
  1051. 526.  
  1052.   
  1053. 527.try:  
  1054.   
  1055. 528.    from strop import maketrans, lowercase, uppercase, whitespace  
  1056.   
  1057. 529.    letters = lowercase + uppercase  
  1058.   
  1059. 530.except ImportError:  
  1060.   
  1061. 531.    pass # Use the original versions  
  1062.   
  1063. 532.  
  1064.   
  1065. 533.########################################################################  
  1066.   
  1067. 534.# the Formatter class  
  1068.   
  1069. 535.# see PEP 3101 for details and purpose of this class  
  1070.   
  1071. 536.  
  1072.   
  1073. 537.# The hard parts are reused from the C implementation. They're exposed as "_"  
  1074.   
  1075. 538.# prefixed methods of str and unicode.  
  1076.   
  1077. 539.  
  1078.   
  1079. 540.# The overall parser is implemented in str._formatter_parser.  
  1080.   
  1081. 541.# The field name parser is implemented in str._formatter_field_name_split  
  1082.   
  1083. 542.  
  1084.   
  1085. 543.class Formatter(object):  
  1086.   
  1087. 544.    def format(self, format_string, *args, **kwargs):  
  1088.   
  1089. 545.        return self.vformat(format_string, args, kwargs)  
  1090.   
  1091. 546.  
  1092.   
  1093. 547.    def vformat(self, format_string, args, kwargs):  
  1094.   
  1095. 548.        used_args = set()  
  1096.   
  1097. 549.        result = self._vformat(format_string, args, kwargs, used_args, 2)  
  1098.   
  1099. 550.        self.check_unused_args(used_args, args, kwargs)  
  1100.   
  1101. 551.        return result  
  1102.   
  1103. 552.  
  1104.   
  1105. 553.    def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):  
  1106.   
  1107. 554.        if recursion_depth < 0:  
  1108.   
  1109. 555.            raise ValueError('Max string recursion exceeded')  
  1110.   
  1111. 556.        result = []  
  1112.   
  1113. 557.        for literal_text, field_name, format_spec, conversion in   
  1114.   
  1115. 558.                self.parse(format_string):  
  1116.   
  1117. 559.  
  1118.   
  1119. 560.            # output the literal text  
  1120.   
  1121. 561.            if literal_text:  
  1122.   
  1123. 562.                result.append(literal_text)  
  1124.   
  1125. 563.  
  1126.   
  1127. 564.            # if there's a field, output it  
  1128.   
  1129. 565.            if field_name is not None:  
  1130.   
  1131. 566.                # this is some markup, find the object and do  
  1132.   
  1133. 567.                # the formatting  
  1134.   
  1135. 568.  
  1136.   
  1137. 569.                # given the field_name, find the object it references  
  1138.   
  1139. 570.                # and the argument it came from  
  1140.   
  1141. 571.                obj, arg_used = self.get_field(field_name, args, kwargs)  
  1142.   
  1143. 572.                used_args.add(arg_used)  
  1144.   
  1145. 573.  
  1146.   
  1147. 574.                # do any conversion on the resulting object  
  1148.   
  1149. 575.                obj = self.convert_field(obj, conversion)  
  1150.   
  1151. 576.  
  1152.   
  1153. 577.                # expand the format spec, if needed  
  1154.   
  1155. 578.                format_spec = self._vformat(format_spec, args, kwargs,  
  1156.   
  1157. 579.                                            used_args, recursion_depth-1)  
  1158.   
  1159. 580.  
  1160.   
  1161. 581.                # format the object and append to the result  
  1162.   
  1163. 582.                result.append(self.format_field(obj, format_spec))  
  1164.   
  1165. 583.  
  1166.   
  1167. 584.        return ''.join(result)  
  1168.   
  1169. 585.  
  1170.   
  1171. 586.  
  1172.   
  1173. 587.    def get_value(self, key, args, kwargs):  
  1174.   
  1175. 588.        if isinstance(key, (int, long)):  
  1176.   
  1177. 589.            return args[key]  
  1178.   
  1179. 590.        else:  
  1180.   
  1181. 591.            return kwargs[key]  
  1182.   
  1183. 592.  
  1184.   
  1185. 593.  
  1186.   
  1187. 594.    def check_unused_args(self, used_args, args, kwargs):  
  1188.   
  1189. 595.        pass  
  1190.   
  1191. 596.  
  1192.   
  1193. 597.  
  1194.   
  1195. 598.    def format_field(self, value, format_spec):  
  1196.   
  1197. 599.        return format(value, format_spec)  
  1198.   
  1199. 600.  
  1200.   
  1201. 601.  
  1202.   
  1203. 602.    def convert_field(self, value, conversion):  
  1204.   
  1205. 603.        # do any conversion on the resulting object  
  1206.   
  1207. 604.        if conversion == 'r':  
  1208.   
  1209. 605.            return repr(value)  
  1210.   
  1211. 606.        elif conversion == 's':  
  1212.   
  1213. 607.            return str(value)  
  1214.   
  1215. 608.        elif conversion is None:  
  1216.   
  1217. 609.            return value  
  1218.   
  1219. 610.        raise ValueError("Unknown converion specifier {0!s}".format(conversion))  
  1220.   
  1221. 611.  
  1222.   
  1223. 612.  
  1224.   
  1225. 613.    # returns an iterable that contains tuples of the form:  
  1226.   
  1227. 614.    # (literal_text, field_name, format_spec, conversion)  
  1228.   
  1229. 615.    # literal_text can be zero length  
  1230.   
  1231. 616.    # field_name can be None, in which case there's no  
  1232.   
  1233. 617.    # object to format and output  
  1234.   
  1235. 618.    # if field_name is not None, it is looked up, formatted  
  1236.   
  1237. 619.    # with format_spec and conversion and then used  
  1238.   
  1239. 620.    def parse(self, format_string):  
  1240.   
  1241. 621.        return format_string._formatter_parser()  
  1242.   
  1243. 622.  
  1244.   
  1245. 623.  
  1246.   
  1247. 624.    # given a field_name, find the object it references.  
  1248.   
  1249. 625.    # field_name: the field being looked up, e.g. "0.name"  
  1250.   
  1251. 626.    # or "lookup[3]"  
  1252.   
  1253. 627.    # used_args: a set of which args have been used  
  1254.   
  1255. 628.    # args, kwargs: as passed in to vformat  
  1256.   
  1257. 629.    def get_field(self, field_name, args, kwargs):  
  1258.   
  1259. 630.        first, rest = field_name._formatter_field_name_split()  
  1260.   
  1261. 631.  
  1262.   
  1263. 632.        obj = self.get_value(first, args, kwargs)  
  1264.   
  1265. 633.  
  1266.   
  1267. 634.        # loop through the rest of the field_name, doing  
  1268.   
  1269. 635.        # getattr or getitem as needed  
  1270.   
  1271. 636.        for is_attr, i in rest:  
  1272.   
  1273. 637.            if is_attr:  
  1274.   
  1275. 638.                obj = getattr(obj, i)  
  1276.   
  1277. 639.            else:  
  1278.   
  1279. 640.                obj = obj[i]  
  1280.   
  1281. 641.  
  1282.   
  1283. 642.        return obj, first  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值