home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / string.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  19.2 KB  |  579 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """A collection of string operations (most are no longer used).
  5.  
  6. Warning: most of the code you see here isn't normally used nowadays.
  7. Beginning with Python 1.6, many of these functions are implemented as
  8. methods on the standard string object. They used to be implemented by
  9. a built-in module called strop, but strop is now obsolete itself.
  10.  
  11. Public module variables:
  12.  
  13. whitespace -- a string containing all characters considered whitespace
  14. lowercase -- a string containing all characters considered lowercase letters
  15. uppercase -- a string containing all characters considered uppercase letters
  16. letters -- a string containing all characters considered letters
  17. digits -- a string containing all characters considered decimal digits
  18. hexdigits -- a string containing all characters considered hexadecimal digits
  19. octdigits -- a string containing all characters considered octal digits
  20. punctuation -- a string containing all characters considered punctuation
  21. printable -- a string containing all characters considered printable
  22.  
  23. """
  24. whitespace = ' \t\n\r\x0b\x0c'
  25. lowercase = 'abcdefghijklmnopqrstuvwxyz'
  26. uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  27. letters = lowercase + uppercase
  28. ascii_lowercase = lowercase
  29. ascii_uppercase = uppercase
  30. ascii_letters = ascii_lowercase + ascii_uppercase
  31. digits = '0123456789'
  32. hexdigits = digits + 'abcdef' + 'ABCDEF'
  33. octdigits = '01234567'
  34. punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
  35. printable = digits + letters + punctuation + whitespace
  36. l = map(chr, xrange(256))
  37. _idmap = str('').join(l)
  38. del l
  39.  
  40. def capwords(s, sep = None):
  41.     '''capwords(s, [sep]) -> string
  42.  
  43.     Split the argument into words using split, capitalize each
  44.     word using capitalize, and join the capitalized words using
  45.     join. Note that this replaces runs of whitespace characters by
  46.     a single space.
  47.  
  48.     '''
  49.     if not sep:
  50.         pass
  51.     return []([ x.capitalize() for x in s.split(sep) ])
  52.  
  53. _idmapL = None
  54.  
  55. def maketrans(fromstr, tostr):
  56.     '''maketrans(frm, to) -> string
  57.  
  58.     Return a translation table (a string of 256 bytes long)
  59.     suitable for use in string.translate.  The strings frm and to
  60.     must be of the same length.
  61.  
  62.     '''
  63.     global _idmapL
  64.     if len(fromstr) != len(tostr):
  65.         raise ValueError, 'maketrans arguments must have same length'
  66.     len(fromstr) != len(tostr)
  67.     if not _idmapL:
  68.         _idmapL = list(_idmap)
  69.     
  70.     L = _idmapL[:]
  71.     fromstr = map(ord, fromstr)
  72.     for i in range(len(fromstr)):
  73.         L[fromstr[i]] = tostr[i]
  74.     
  75.     return ''.join(L)
  76.  
  77. import re as _re
  78.  
  79. class _multimap:
  80.     '''Helper class for combining multiple mappings.
  81.  
  82.     Used by .{safe_,}substitute() to combine the mapping and keyword
  83.     arguments.
  84.     '''
  85.     
  86.     def __init__(self, primary, secondary):
  87.         self._primary = primary
  88.         self._secondary = secondary
  89.  
  90.     
  91.     def __getitem__(self, key):
  92.         
  93.         try:
  94.             return self._primary[key]
  95.         except KeyError:
  96.             return self._secondary[key]
  97.  
  98.  
  99.  
  100.  
  101. class _TemplateMetaclass(type):
  102.     pattern = '\n    %(delim)s(?:\n      (?P<escaped>%(delim)s) |   # Escape sequence of two delimiters\n      (?P<named>%(id)s)      |   # delimiter and a Python identifier\n      {(?P<braced>%(id)s)}   |   # delimiter and a braced identifier\n      (?P<invalid>)              # Other ill-formed delimiter exprs\n    )\n    '
  103.     
  104.     def __init__(cls, name, bases, dct):
  105.         super(_TemplateMetaclass, cls).__init__(name, bases, dct)
  106.         if 'pattern' in dct:
  107.             pattern = cls.pattern
  108.         else:
  109.             pattern = _TemplateMetaclass.pattern % {
  110.                 'delim': _re.escape(cls.delimiter),
  111.                 'id': cls.idpattern }
  112.         cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
  113.  
  114.  
  115.  
  116. class Template:
  117.     '''A string class for supporting $-substitutions.'''
  118.     __metaclass__ = _TemplateMetaclass
  119.     delimiter = '$'
  120.     idpattern = '[_a-z][_a-z0-9]*'
  121.     
  122.     def __init__(self, template):
  123.         self.template = template
  124.  
  125.     
  126.     def _invalid(self, mo):
  127.         i = mo.start('invalid')
  128.         lines = self.template[:i].splitlines(True)
  129.         if not lines:
  130.             colno = 1
  131.             lineno = 1
  132.         else:
  133.             colno = i - len(''.join(lines[:-1]))
  134.             lineno = len(lines)
  135.         raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno))
  136.  
  137.     
  138.     def substitute(self, *args, **kws):
  139.         if len(args) > 1:
  140.             raise TypeError('Too many positional arguments')
  141.         len(args) > 1
  142.         if not args:
  143.             mapping = kws
  144.         elif kws:
  145.             mapping = _multimap(kws, args[0])
  146.         else:
  147.             mapping = args[0]
  148.         
  149.         def convert(mo):
  150.             if not mo.group('named'):
  151.                 pass
  152.             named = mo.group('braced')
  153.             if named is not None:
  154.                 val = mapping[named]
  155.                 return '%s' % (val,)
  156.             if mo.group('escaped') is not None:
  157.                 return self.delimiter
  158.             raise ValueError('Unrecognized named group in pattern', self.pattern)
  159.  
  160.         return self.pattern.sub(convert, self.template)
  161.  
  162.     
  163.     def safe_substitute(self, *args, **kws):
  164.         if len(args) > 1:
  165.             raise TypeError('Too many positional arguments')
  166.         len(args) > 1
  167.         if not args:
  168.             mapping = kws
  169.         elif kws:
  170.             mapping = _multimap(kws, args[0])
  171.         else:
  172.             mapping = args[0]
  173.         
  174.         def convert(mo):
  175.             named = mo.group('named')
  176.             if named is not None:
  177.                 
  178.                 try:
  179.                     return '%s' % (mapping[named],)
  180.                 except KeyError:
  181.                     return self.delimiter + named
  182.                 
  183.  
  184.             None<EXCEPTION MATCH>KeyError
  185.             braced = mo.group('braced')
  186.             if braced is not None:
  187.                 
  188.                 try:
  189.                     return '%s' % (mapping[braced],)
  190.                 except KeyError:
  191.                     return self.delimiter + '{' + braced + '}'
  192.                 
  193.  
  194.             None<EXCEPTION MATCH>KeyError
  195.             if mo.group('escaped') is not None:
  196.                 return self.delimiter
  197.             if mo.group('invalid') is not None:
  198.                 return self.delimiter
  199.             raise ValueError('Unrecognized named group in pattern', self.pattern)
  200.  
  201.         return self.pattern.sub(convert, self.template)
  202.  
  203.  
  204. index_error = ValueError
  205. atoi_error = ValueError
  206. atof_error = ValueError
  207. atol_error = ValueError
  208.  
  209. def lower(s):
  210.     '''lower(s) -> string
  211.  
  212.     Return a copy of the string s converted to lowercase.
  213.  
  214.     '''
  215.     return s.lower()
  216.  
  217.  
  218. def upper(s):
  219.     '''upper(s) -> string
  220.  
  221.     Return a copy of the string s converted to uppercase.
  222.  
  223.     '''
  224.     return s.upper()
  225.  
  226.  
  227. def swapcase(s):
  228.     '''swapcase(s) -> string
  229.  
  230.     Return a copy of the string s with upper case characters
  231.     converted to lowercase and vice versa.
  232.  
  233.     '''
  234.     return s.swapcase()
  235.  
  236.  
  237. def strip(s, chars = None):
  238.     '''strip(s [,chars]) -> string
  239.  
  240.     Return a copy of the string s with leading and trailing
  241.     whitespace removed.
  242.     If chars is given and not None, remove characters in chars instead.
  243.     If chars is unicode, S will be converted to unicode before stripping.
  244.  
  245.     '''
  246.     return s.strip(chars)
  247.  
  248.  
  249. def lstrip(s, chars = None):
  250.     '''lstrip(s [,chars]) -> string
  251.  
  252.     Return a copy of the string s with leading whitespace removed.
  253.     If chars is given and not None, remove characters in chars instead.
  254.  
  255.     '''
  256.     return s.lstrip(chars)
  257.  
  258.  
  259. def rstrip(s, chars = None):
  260.     '''rstrip(s [,chars]) -> string
  261.  
  262.     Return a copy of the string s with trailing whitespace removed.
  263.     If chars is given and not None, remove characters in chars instead.
  264.  
  265.     '''
  266.     return s.rstrip(chars)
  267.  
  268.  
  269. def split(s, sep = None, maxsplit = -1):
  270.     '''split(s [,sep [,maxsplit]]) -> list of strings
  271.  
  272.     Return a list of the words in the string s, using sep as the
  273.     delimiter string.  If maxsplit is given, splits at no more than
  274.     maxsplit places (resulting in at most maxsplit+1 words).  If sep
  275.     is not specified or is None, any whitespace string is a separator.
  276.  
  277.     (split and splitfields are synonymous)
  278.  
  279.     '''
  280.     return s.split(sep, maxsplit)
  281.  
  282. splitfields = split
  283.  
  284. def rsplit(s, sep = None, maxsplit = -1):
  285.     '''rsplit(s [,sep [,maxsplit]]) -> list of strings
  286.  
  287.     Return a list of the words in the string s, using sep as the
  288.     delimiter string, starting at the end of the string and working
  289.     to the front.  If maxsplit is given, at most maxsplit splits are
  290.     done. If sep is not specified or is None, any whitespace string
  291.     is a separator.
  292.     '''
  293.     return s.rsplit(sep, maxsplit)
  294.  
  295.  
  296. def join(words, sep = ' '):
  297.     '''join(list [,sep]) -> string
  298.  
  299.     Return a string composed of the words in list, with
  300.     intervening occurrences of sep.  The default separator is a
  301.     single space.
  302.  
  303.     (joinfields and join are synonymous)
  304.  
  305.     '''
  306.     return sep.join(words)
  307.  
  308. joinfields = join
  309.  
  310. def index(s, *args):
  311.     '''index(s, sub [,start [,end]]) -> int
  312.  
  313.     Like find but raises ValueError when the substring is not found.
  314.  
  315.     '''
  316.     return s.index(*args)
  317.  
  318.  
  319. def rindex(s, *args):
  320.     '''rindex(s, sub [,start [,end]]) -> int
  321.  
  322.     Like rfind but raises ValueError when the substring is not found.
  323.  
  324.     '''
  325.     return s.rindex(*args)
  326.  
  327.  
  328. def count(s, *args):
  329.     '''count(s, sub[, start[,end]]) -> int
  330.  
  331.     Return the number of occurrences of substring sub in string
  332.     s[start:end].  Optional arguments start and end are
  333.     interpreted as in slice notation.
  334.  
  335.     '''
  336.     return s.count(*args)
  337.  
  338.  
  339. def find(s, *args):
  340.     '''find(s, sub [,start [,end]]) -> in
  341.  
  342.     Return the lowest index in s where substring sub is found,
  343.     such that sub is contained within s[start,end].  Optional
  344.     arguments start and end are interpreted as in slice notation.
  345.  
  346.     Return -1 on failure.
  347.  
  348.     '''
  349.     return s.find(*args)
  350.  
  351.  
  352. def rfind(s, *args):
  353.     '''rfind(s, sub [,start [,end]]) -> int
  354.  
  355.     Return the highest index in s where substring sub is found,
  356.     such that sub is contained within s[start,end].  Optional
  357.     arguments start and end are interpreted as in slice notation.
  358.  
  359.     Return -1 on failure.
  360.  
  361.     '''
  362.     return s.rfind(*args)
  363.  
  364. _float = float
  365. _int = int
  366. _long = long
  367.  
  368. def atof(s):
  369.     '''atof(s) -> float
  370.  
  371.     Return the floating point number represented by the string s.
  372.  
  373.     '''
  374.     return _float(s)
  375.  
  376.  
  377. def atoi(s, base = 10):
  378.     '''atoi(s [,base]) -> int
  379.  
  380.     Return the integer represented by the string s in the given
  381.     base, which defaults to 10.  The string s must consist of one
  382.     or more digits, possibly preceded by a sign.  If base is 0, it
  383.     is chosen from the leading characters of s, 0 for octal, 0x or
  384.     0X for hexadecimal.  If base is 16, a preceding 0x or 0X is
  385.     accepted.
  386.  
  387.     '''
  388.     return _int(s, base)
  389.  
  390.  
  391. def atol(s, base = 10):
  392.     '''atol(s [,base]) -> long
  393.  
  394.     Return the long integer represented by the string s in the
  395.     given base, which defaults to 10.  The string s must consist
  396.     of one or more digits, possibly preceded by a sign.  If base
  397.     is 0, it is chosen from the leading characters of s, 0 for
  398.     octal, 0x or 0X for hexadecimal.  If base is 16, a preceding
  399.     0x or 0X is accepted.  A trailing L or l is not accepted,
  400.     unless base is 0.
  401.  
  402.     '''
  403.     return _long(s, base)
  404.  
  405.  
  406. def ljust(s, width, *args):
  407.     '''ljust(s, width[, fillchar]) -> string
  408.  
  409.     Return a left-justified version of s, in a field of the
  410.     specified width, padded with spaces as needed.  The string is
  411.     never truncated.  If specified the fillchar is used instead of spaces.
  412.  
  413.     '''
  414.     return s.ljust(width, *args)
  415.  
  416.  
  417. def rjust(s, width, *args):
  418.     '''rjust(s, width[, fillchar]) -> string
  419.  
  420.     Return a right-justified version of s, in a field of the
  421.     specified width, padded with spaces as needed.  The string is
  422.     never truncated.  If specified the fillchar is used instead of spaces.
  423.  
  424.     '''
  425.     return s.rjust(width, *args)
  426.  
  427.  
  428. def center(s, width, *args):
  429.     '''center(s, width[, fillchar]) -> string
  430.  
  431.     Return a center version of s, in a field of the specified
  432.     width. padded with spaces as needed.  The string is never
  433.     truncated.  If specified the fillchar is used instead of spaces.
  434.  
  435.     '''
  436.     return s.center(width, *args)
  437.  
  438.  
  439. def zfill(x, width):
  440.     '''zfill(x, width) -> string
  441.  
  442.     Pad a numeric string x with zeros on the left, to fill a field
  443.     of the specified width.  The string x is never truncated.
  444.  
  445.     '''
  446.     if not isinstance(x, basestring):
  447.         x = repr(x)
  448.     
  449.     return x.zfill(width)
  450.  
  451.  
  452. def expandtabs(s, tabsize = 8):
  453.     '''expandtabs(s [,tabsize]) -> string
  454.  
  455.     Return a copy of the string s with all tab characters replaced
  456.     by the appropriate number of spaces, depending on the current
  457.     column, and the tabsize (default 8).
  458.  
  459.     '''
  460.     return s.expandtabs(tabsize)
  461.  
  462.  
  463. def translate(s, table, deletions = ''):
  464.     '''translate(s,table [,deletions]) -> string
  465.  
  466.     Return a copy of the string s, where all characters occurring
  467.     in the optional argument deletions are removed, and the
  468.     remaining characters have been mapped through the given
  469.     translation table, which must be a string of length 256.  The
  470.     deletions argument is not allowed for Unicode strings.
  471.  
  472.     '''
  473.     if deletions or table is None:
  474.         return s.translate(table, deletions)
  475.     return s.translate(table + s[:0])
  476.  
  477.  
  478. def capitalize(s):
  479.     '''capitalize(s) -> string
  480.  
  481.     Return a copy of the string s with only its first character
  482.     capitalized.
  483.  
  484.     '''
  485.     return s.capitalize()
  486.  
  487.  
  488. def replace(s, old, new, maxsplit = -1):
  489.     '''replace (str, old, new[, maxsplit]) -> string
  490.  
  491.     Return a copy of string str with all occurrences of substring
  492.     old replaced by new. If the optional argument maxsplit is
  493.     given, only the first maxsplit occurrences are replaced.
  494.  
  495.     '''
  496.     return s.replace(old, new, maxsplit)
  497.  
  498.  
  499. try:
  500.     from strop import maketrans, lowercase, uppercase, whitespace
  501.     letters = lowercase + uppercase
  502. except ImportError:
  503.     pass
  504.  
  505.  
  506. class Formatter(object):
  507.     
  508.     def format(self, format_string, *args, **kwargs):
  509.         return self.vformat(format_string, args, kwargs)
  510.  
  511.     
  512.     def vformat(self, format_string, args, kwargs):
  513.         used_args = set()
  514.         result = self._vformat(format_string, args, kwargs, used_args, 2)
  515.         self.check_unused_args(used_args, args, kwargs)
  516.         return result
  517.  
  518.     
  519.     def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
  520.         if recursion_depth < 0:
  521.             raise ValueError('Max string recursion exceeded')
  522.         recursion_depth < 0
  523.         result = []
  524.         for literal_text, field_name, format_spec, conversion in self.parse(format_string):
  525.             if literal_text:
  526.                 result.append(literal_text)
  527.             
  528.             if field_name is not None:
  529.                 (obj, arg_used) = self.get_field(field_name, args, kwargs)
  530.                 used_args.add(arg_used)
  531.                 obj = self.convert_field(obj, conversion)
  532.                 format_spec = self._vformat(format_spec, args, kwargs, used_args, recursion_depth - 1)
  533.                 result.append(self.format_field(obj, format_spec))
  534.                 continue
  535.         
  536.         return ''.join(result)
  537.  
  538.     
  539.     def get_value(self, key, args, kwargs):
  540.         if isinstance(key, (int, long)):
  541.             return args[key]
  542.         return kwargs[key]
  543.  
  544.     
  545.     def check_unused_args(self, used_args, args, kwargs):
  546.         pass
  547.  
  548.     
  549.     def format_field(self, value, format_spec):
  550.         return format(value, format_spec)
  551.  
  552.     
  553.     def convert_field(self, value, conversion):
  554.         if conversion == 'r':
  555.             return repr(value)
  556.         if conversion == 's':
  557.             return str(value)
  558.         if conversion is None:
  559.             return value
  560.         raise ValueError('Unknown converion specifier {0!s}'.format(conversion))
  561.  
  562.     
  563.     def parse(self, format_string):
  564.         return format_string._formatter_parser()
  565.  
  566.     
  567.     def get_field(self, field_name, args, kwargs):
  568.         (first, rest) = field_name._formatter_field_name_split()
  569.         obj = self.get_value(first, args, kwargs)
  570.         for is_attr, i in rest:
  571.             if is_attr:
  572.                 obj = getattr(obj, i)
  573.                 continue
  574.             obj = obj[i]
  575.         
  576.         return (obj, first)
  577.  
  578.  
  579.