]> git.proxmox.com Git - mirror_edk2.git/blobdiff - AppPkg/Applications/Python/Python-2.7.10/Lib/string.py
AppPkg/Applications/Python/Python-2.7.10: Initial Checkin part 4/5.
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / Lib / string.py
diff --git a/AppPkg/Applications/Python/Python-2.7.10/Lib/string.py b/AppPkg/Applications/Python/Python-2.7.10/Lib/string.py
new file mode 100644 (file)
index 0000000..3509872
--- /dev/null
@@ -0,0 +1,656 @@
+"""A collection of string operations (most are no longer used).\r
+\r
+Warning: most of the code you see here isn't normally used nowadays.\r
+Beginning with Python 1.6, many of these functions are implemented as\r
+methods on the standard string object. They used to be implemented by\r
+a built-in module called strop, but strop is now obsolete itself.\r
+\r
+Public module variables:\r
+\r
+whitespace -- a string containing all characters considered whitespace\r
+lowercase -- a string containing all characters considered lowercase letters\r
+uppercase -- a string containing all characters considered uppercase letters\r
+letters -- a string containing all characters considered letters\r
+digits -- a string containing all characters considered decimal digits\r
+hexdigits -- a string containing all characters considered hexadecimal digits\r
+octdigits -- a string containing all characters considered octal digits\r
+punctuation -- a string containing all characters considered punctuation\r
+printable -- a string containing all characters considered printable\r
+\r
+"""\r
+\r
+# Some strings for ctype-style character classification\r
+whitespace = ' \t\n\r\v\f'\r
+lowercase = 'abcdefghijklmnopqrstuvwxyz'\r
+uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\r
+letters = lowercase + uppercase\r
+ascii_lowercase = lowercase\r
+ascii_uppercase = uppercase\r
+ascii_letters = ascii_lowercase + ascii_uppercase\r
+digits = '0123456789'\r
+hexdigits = digits + 'abcdef' + 'ABCDEF'\r
+octdigits = '01234567'\r
+punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""\r
+printable = digits + letters + punctuation + whitespace\r
+\r
+# Case conversion helpers\r
+# Use str to convert Unicode literal in case of -U\r
+l = map(chr, xrange(256))\r
+_idmap = str('').join(l)\r
+del l\r
+\r
+# Functions which aren't available as string methods.\r
+\r
+# Capitalize the words in a string, e.g. " aBc  dEf " -> "Abc Def".\r
+def capwords(s, sep=None):\r
+    """capwords(s [,sep]) -> string\r
+\r
+    Split the argument into words using split, capitalize each\r
+    word using capitalize, and join the capitalized words using\r
+    join.  If the optional second argument sep is absent or None,\r
+    runs of whitespace characters are replaced by a single space\r
+    and leading and trailing whitespace are removed, otherwise\r
+    sep is used to split and join the words.\r
+\r
+    """\r
+    return (sep or ' ').join(x.capitalize() for x in s.split(sep))\r
+\r
+\r
+# Construct a translation string\r
+_idmapL = None\r
+def maketrans(fromstr, tostr):\r
+    """maketrans(frm, to) -> string\r
+\r
+    Return a translation table (a string of 256 bytes long)\r
+    suitable for use in string.translate.  The strings frm and to\r
+    must be of the same length.\r
+\r
+    """\r
+    if len(fromstr) != len(tostr):\r
+        raise ValueError, "maketrans arguments must have same length"\r
+    global _idmapL\r
+    if not _idmapL:\r
+        _idmapL = list(_idmap)\r
+    L = _idmapL[:]\r
+    fromstr = map(ord, fromstr)\r
+    for i in range(len(fromstr)):\r
+        L[fromstr[i]] = tostr[i]\r
+    return ''.join(L)\r
+\r
+\r
+\r
+####################################################################\r
+import re as _re\r
+\r
+class _multimap:\r
+    """Helper class for combining multiple mappings.\r
+\r
+    Used by .{safe_,}substitute() to combine the mapping and keyword\r
+    arguments.\r
+    """\r
+    def __init__(self, primary, secondary):\r
+        self._primary = primary\r
+        self._secondary = secondary\r
+\r
+    def __getitem__(self, key):\r
+        try:\r
+            return self._primary[key]\r
+        except KeyError:\r
+            return self._secondary[key]\r
+\r
+\r
+class _TemplateMetaclass(type):\r
+    pattern = r"""\r
+    %(delim)s(?:\r
+      (?P<escaped>%(delim)s) |   # Escape sequence of two delimiters\r
+      (?P<named>%(id)s)      |   # delimiter and a Python identifier\r
+      {(?P<braced>%(id)s)}   |   # delimiter and a braced identifier\r
+      (?P<invalid>)              # Other ill-formed delimiter exprs\r
+    )\r
+    """\r
+\r
+    def __init__(cls, name, bases, dct):\r
+        super(_TemplateMetaclass, cls).__init__(name, bases, dct)\r
+        if 'pattern' in dct:\r
+            pattern = cls.pattern\r
+        else:\r
+            pattern = _TemplateMetaclass.pattern % {\r
+                'delim' : _re.escape(cls.delimiter),\r
+                'id'    : cls.idpattern,\r
+                }\r
+        cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)\r
+\r
+\r
+class Template:\r
+    """A string class for supporting $-substitutions."""\r
+    __metaclass__ = _TemplateMetaclass\r
+\r
+    delimiter = '$'\r
+    idpattern = r'[_a-z][_a-z0-9]*'\r
+\r
+    def __init__(self, template):\r
+        self.template = template\r
+\r
+    # Search for $$, $identifier, ${identifier}, and any bare $'s\r
+\r
+    def _invalid(self, mo):\r
+        i = mo.start('invalid')\r
+        lines = self.template[:i].splitlines(True)\r
+        if not lines:\r
+            colno = 1\r
+            lineno = 1\r
+        else:\r
+            colno = i - len(''.join(lines[:-1]))\r
+            lineno = len(lines)\r
+        raise ValueError('Invalid placeholder in string: line %d, col %d' %\r
+                         (lineno, colno))\r
+\r
+    def substitute(*args, **kws):\r
+        if not args:\r
+            raise TypeError("descriptor 'substitute' of 'Template' object "\r
+                            "needs an argument")\r
+        self, args = args[0], args[1:]  # allow the "self" keyword be passed\r
+        if len(args) > 1:\r
+            raise TypeError('Too many positional arguments')\r
+        if not args:\r
+            mapping = kws\r
+        elif kws:\r
+            mapping = _multimap(kws, args[0])\r
+        else:\r
+            mapping = args[0]\r
+        # Helper function for .sub()\r
+        def convert(mo):\r
+            # Check the most common path first.\r
+            named = mo.group('named') or mo.group('braced')\r
+            if named is not None:\r
+                val = mapping[named]\r
+                # We use this idiom instead of str() because the latter will\r
+                # fail if val is a Unicode containing non-ASCII characters.\r
+                return '%s' % (val,)\r
+            if mo.group('escaped') is not None:\r
+                return self.delimiter\r
+            if mo.group('invalid') is not None:\r
+                self._invalid(mo)\r
+            raise ValueError('Unrecognized named group in pattern',\r
+                             self.pattern)\r
+        return self.pattern.sub(convert, self.template)\r
+\r
+    def safe_substitute(*args, **kws):\r
+        if not args:\r
+            raise TypeError("descriptor 'safe_substitute' of 'Template' object "\r
+                            "needs an argument")\r
+        self, args = args[0], args[1:]  # allow the "self" keyword be passed\r
+        if len(args) > 1:\r
+            raise TypeError('Too many positional arguments')\r
+        if not args:\r
+            mapping = kws\r
+        elif kws:\r
+            mapping = _multimap(kws, args[0])\r
+        else:\r
+            mapping = args[0]\r
+        # Helper function for .sub()\r
+        def convert(mo):\r
+            named = mo.group('named') or mo.group('braced')\r
+            if named is not None:\r
+                try:\r
+                    # We use this idiom instead of str() because the latter\r
+                    # will fail if val is a Unicode containing non-ASCII\r
+                    return '%s' % (mapping[named],)\r
+                except KeyError:\r
+                    return mo.group()\r
+            if mo.group('escaped') is not None:\r
+                return self.delimiter\r
+            if mo.group('invalid') is not None:\r
+                return mo.group()\r
+            raise ValueError('Unrecognized named group in pattern',\r
+                             self.pattern)\r
+        return self.pattern.sub(convert, self.template)\r
+\r
+\r
+\r
+####################################################################\r
+# NOTE: Everything below here is deprecated.  Use string methods instead.\r
+# This stuff will go away in Python 3.0.\r
+\r
+# Backward compatible names for exceptions\r
+index_error = ValueError\r
+atoi_error = ValueError\r
+atof_error = ValueError\r
+atol_error = ValueError\r
+\r
+# convert UPPER CASE letters to lower case\r
+def lower(s):\r
+    """lower(s) -> string\r
+\r
+    Return a copy of the string s converted to lowercase.\r
+\r
+    """\r
+    return s.lower()\r
+\r
+# Convert lower case letters to UPPER CASE\r
+def upper(s):\r
+    """upper(s) -> string\r
+\r
+    Return a copy of the string s converted to uppercase.\r
+\r
+    """\r
+    return s.upper()\r
+\r
+# Swap lower case letters and UPPER CASE\r
+def swapcase(s):\r
+    """swapcase(s) -> string\r
+\r
+    Return a copy of the string s with upper case characters\r
+    converted to lowercase and vice versa.\r
+\r
+    """\r
+    return s.swapcase()\r
+\r
+# Strip leading and trailing tabs and spaces\r
+def strip(s, chars=None):\r
+    """strip(s [,chars]) -> string\r
+\r
+    Return a copy of the string s with leading and trailing\r
+    whitespace removed.\r
+    If chars is given and not None, remove characters in chars instead.\r
+    If chars is unicode, S will be converted to unicode before stripping.\r
+\r
+    """\r
+    return s.strip(chars)\r
+\r
+# Strip leading tabs and spaces\r
+def lstrip(s, chars=None):\r
+    """lstrip(s [,chars]) -> string\r
+\r
+    Return a copy of the string s with leading whitespace removed.\r
+    If chars is given and not None, remove characters in chars instead.\r
+\r
+    """\r
+    return s.lstrip(chars)\r
+\r
+# Strip trailing tabs and spaces\r
+def rstrip(s, chars=None):\r
+    """rstrip(s [,chars]) -> string\r
+\r
+    Return a copy of the string s with trailing whitespace removed.\r
+    If chars is given and not None, remove characters in chars instead.\r
+\r
+    """\r
+    return s.rstrip(chars)\r
+\r
+\r
+# Split a string into a list of space/tab-separated words\r
+def split(s, sep=None, maxsplit=-1):\r
+    """split(s [,sep [,maxsplit]]) -> list of strings\r
+\r
+    Return a list of the words in the string s, using sep as the\r
+    delimiter string.  If maxsplit is given, splits at no more than\r
+    maxsplit places (resulting in at most maxsplit+1 words).  If sep\r
+    is not specified or is None, any whitespace string is a separator.\r
+\r
+    (split and splitfields are synonymous)\r
+\r
+    """\r
+    return s.split(sep, maxsplit)\r
+splitfields = split\r
+\r
+# Split a string into a list of space/tab-separated words\r
+def rsplit(s, sep=None, maxsplit=-1):\r
+    """rsplit(s [,sep [,maxsplit]]) -> list of strings\r
+\r
+    Return a list of the words in the string s, using sep as the\r
+    delimiter string, starting at the end of the string and working\r
+    to the front.  If maxsplit is given, at most maxsplit splits are\r
+    done. If sep is not specified or is None, any whitespace string\r
+    is a separator.\r
+    """\r
+    return s.rsplit(sep, maxsplit)\r
+\r
+# Join fields with optional separator\r
+def join(words, sep = ' '):\r
+    """join(list [,sep]) -> string\r
+\r
+    Return a string composed of the words in list, with\r
+    intervening occurrences of sep.  The default separator is a\r
+    single space.\r
+\r
+    (joinfields and join are synonymous)\r
+\r
+    """\r
+    return sep.join(words)\r
+joinfields = join\r
+\r
+# Find substring, raise exception if not found\r
+def index(s, *args):\r
+    """index(s, sub [,start [,end]]) -> int\r
+\r
+    Like find but raises ValueError when the substring is not found.\r
+\r
+    """\r
+    return s.index(*args)\r
+\r
+# Find last substring, raise exception if not found\r
+def rindex(s, *args):\r
+    """rindex(s, sub [,start [,end]]) -> int\r
+\r
+    Like rfind but raises ValueError when the substring is not found.\r
+\r
+    """\r
+    return s.rindex(*args)\r
+\r
+# Count non-overlapping occurrences of substring\r
+def count(s, *args):\r
+    """count(s, sub[, start[,end]]) -> int\r
+\r
+    Return the number of occurrences of substring sub in string\r
+    s[start:end].  Optional arguments start and end are\r
+    interpreted as in slice notation.\r
+\r
+    """\r
+    return s.count(*args)\r
+\r
+# Find substring, return -1 if not found\r
+def find(s, *args):\r
+    """find(s, sub [,start [,end]]) -> in\r
+\r
+    Return the lowest index in s where substring sub is found,\r
+    such that sub is contained within s[start,end].  Optional\r
+    arguments start and end are interpreted as in slice notation.\r
+\r
+    Return -1 on failure.\r
+\r
+    """\r
+    return s.find(*args)\r
+\r
+# Find last substring, return -1 if not found\r
+def rfind(s, *args):\r
+    """rfind(s, sub [,start [,end]]) -> int\r
+\r
+    Return the highest index in s where substring sub is found,\r
+    such that sub is contained within s[start,end].  Optional\r
+    arguments start and end are interpreted as in slice notation.\r
+\r
+    Return -1 on failure.\r
+\r
+    """\r
+    return s.rfind(*args)\r
+\r
+# for a bit of speed\r
+_float = float\r
+_int = int\r
+_long = long\r
+\r
+# Convert string to float\r
+def atof(s):\r
+    """atof(s) -> float\r
+\r
+    Return the floating point number represented by the string s.\r
+\r
+    """\r
+    return _float(s)\r
+\r
+\r
+# Convert string to integer\r
+def atoi(s , base=10):\r
+    """atoi(s [,base]) -> int\r
+\r
+    Return the integer represented by the string s in the given\r
+    base, which defaults to 10.  The string s must consist of one\r
+    or more digits, possibly preceded by a sign.  If base is 0, it\r
+    is chosen from the leading characters of s, 0 for octal, 0x or\r
+    0X for hexadecimal.  If base is 16, a preceding 0x or 0X is\r
+    accepted.\r
+\r
+    """\r
+    return _int(s, base)\r
+\r
+\r
+# Convert string to long integer\r
+def atol(s, base=10):\r
+    """atol(s [,base]) -> long\r
+\r
+    Return the long integer represented by the string s in the\r
+    given base, which defaults to 10.  The string s must consist\r
+    of one or more digits, possibly preceded by a sign.  If base\r
+    is 0, it is chosen from the leading characters of s, 0 for\r
+    octal, 0x or 0X for hexadecimal.  If base is 16, a preceding\r
+    0x or 0X is accepted.  A trailing L or l is not accepted,\r
+    unless base is 0.\r
+\r
+    """\r
+    return _long(s, base)\r
+\r
+\r
+# Left-justify a string\r
+def ljust(s, width, *args):\r
+    """ljust(s, width[, fillchar]) -> string\r
+\r
+    Return a left-justified version of s, in a field of the\r
+    specified width, padded with spaces as needed.  The string is\r
+    never truncated.  If specified the fillchar is used instead of spaces.\r
+\r
+    """\r
+    return s.ljust(width, *args)\r
+\r
+# Right-justify a string\r
+def rjust(s, width, *args):\r
+    """rjust(s, width[, fillchar]) -> string\r
+\r
+    Return a right-justified version of s, in a field of the\r
+    specified width, padded with spaces as needed.  The string is\r
+    never truncated.  If specified the fillchar is used instead of spaces.\r
+\r
+    """\r
+    return s.rjust(width, *args)\r
+\r
+# Center a string\r
+def center(s, width, *args):\r
+    """center(s, width[, fillchar]) -> string\r
+\r
+    Return a center version of s, in a field of the specified\r
+    width. padded with spaces as needed.  The string is never\r
+    truncated.  If specified the fillchar is used instead of spaces.\r
+\r
+    """\r
+    return s.center(width, *args)\r
+\r
+# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'\r
+# Decadent feature: the argument may be a string or a number\r
+# (Use of this is deprecated; it should be a string as with ljust c.s.)\r
+def zfill(x, width):\r
+    """zfill(x, width) -> string\r
+\r
+    Pad a numeric string x with zeros on the left, to fill a field\r
+    of the specified width.  The string x is never truncated.\r
+\r
+    """\r
+    if not isinstance(x, basestring):\r
+        x = repr(x)\r
+    return x.zfill(width)\r
+\r
+# Expand tabs in a string.\r
+# Doesn't take non-printing chars into account, but does understand \n.\r
+def expandtabs(s, tabsize=8):\r
+    """expandtabs(s [,tabsize]) -> string\r
+\r
+    Return a copy of the string s with all tab characters replaced\r
+    by the appropriate number of spaces, depending on the current\r
+    column, and the tabsize (default 8).\r
+\r
+    """\r
+    return s.expandtabs(tabsize)\r
+\r
+# Character translation through look-up table.\r
+def translate(s, table, deletions=""):\r
+    """translate(s,table [,deletions]) -> string\r
+\r
+    Return a copy of the string s, where all characters occurring\r
+    in the optional argument deletions are removed, and the\r
+    remaining characters have been mapped through the given\r
+    translation table, which must be a string of length 256.  The\r
+    deletions argument is not allowed for Unicode strings.\r
+\r
+    """\r
+    if deletions or table is None:\r
+        return s.translate(table, deletions)\r
+    else:\r
+        # Add s[:0] so that if s is Unicode and table is an 8-bit string,\r
+        # table is converted to Unicode.  This means that table *cannot*\r
+        # be a dictionary -- for that feature, use u.translate() directly.\r
+        return s.translate(table + s[:0])\r
+\r
+# Capitalize a string, e.g. "aBc  dEf" -> "Abc  def".\r
+def capitalize(s):\r
+    """capitalize(s) -> string\r
+\r
+    Return a copy of the string s with only its first character\r
+    capitalized.\r
+\r
+    """\r
+    return s.capitalize()\r
+\r
+# Substring replacement (global)\r
+def replace(s, old, new, maxreplace=-1):\r
+    """replace (str, old, new[, maxreplace]) -> string\r
+\r
+    Return a copy of string str with all occurrences of substring\r
+    old replaced by new. If the optional argument maxreplace is\r
+    given, only the first maxreplace occurrences are replaced.\r
+\r
+    """\r
+    return s.replace(old, new, maxreplace)\r
+\r
+\r
+# Try importing optional built-in module "strop" -- if it exists,\r
+# it redefines some string operations that are 100-1000 times faster.\r
+# It also defines values for whitespace, lowercase and uppercase\r
+# that match <ctype.h>'s definitions.\r
+\r
+try:\r
+    from strop import maketrans, lowercase, uppercase, whitespace\r
+    letters = lowercase + uppercase\r
+except ImportError:\r
+    pass                                          # Use the original versions\r
+\r
+########################################################################\r
+# the Formatter class\r
+# see PEP 3101 for details and purpose of this class\r
+\r
+# The hard parts are reused from the C implementation.  They're exposed as "_"\r
+# prefixed methods of str and unicode.\r
+\r
+# The overall parser is implemented in str._formatter_parser.\r
+# The field name parser is implemented in str._formatter_field_name_split\r
+\r
+class Formatter(object):\r
+    def format(*args, **kwargs):\r
+        if not args:\r
+            raise TypeError("descriptor 'format' of 'Formatter' object "\r
+                            "needs an argument")\r
+        self, args = args[0], args[1:]  # allow the "self" keyword be passed\r
+        try:\r
+            format_string, args = args[0], args[1:] # allow the "format_string" keyword be passed\r
+        except IndexError:\r
+            if 'format_string' in kwargs:\r
+                format_string = kwargs.pop('format_string')\r
+            else:\r
+                raise TypeError("format() missing 1 required positional "\r
+                                "argument: 'format_string'")\r
+        return self.vformat(format_string, args, kwargs)\r
+\r
+    def vformat(self, format_string, args, kwargs):\r
+        used_args = set()\r
+        result = self._vformat(format_string, args, kwargs, used_args, 2)\r
+        self.check_unused_args(used_args, args, kwargs)\r
+        return result\r
+\r
+    def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):\r
+        if recursion_depth < 0:\r
+            raise ValueError('Max string recursion exceeded')\r
+        result = []\r
+        for literal_text, field_name, format_spec, conversion in \\r
+                self.parse(format_string):\r
+\r
+            # output the literal text\r
+            if literal_text:\r
+                result.append(literal_text)\r
+\r
+            # if there's a field, output it\r
+            if field_name is not None:\r
+                # this is some markup, find the object and do\r
+                #  the formatting\r
+\r
+                # given the field_name, find the object it references\r
+                #  and the argument it came from\r
+                obj, arg_used = self.get_field(field_name, args, kwargs)\r
+                used_args.add(arg_used)\r
+\r
+                # do any conversion on the resulting object\r
+                obj = self.convert_field(obj, conversion)\r
+\r
+                # expand the format spec, if needed\r
+                format_spec = self._vformat(format_spec, args, kwargs,\r
+                                            used_args, recursion_depth-1)\r
+\r
+                # format the object and append to the result\r
+                result.append(self.format_field(obj, format_spec))\r
+\r
+        return ''.join(result)\r
+\r
+\r
+    def get_value(self, key, args, kwargs):\r
+        if isinstance(key, (int, long)):\r
+            return args[key]\r
+        else:\r
+            return kwargs[key]\r
+\r
+\r
+    def check_unused_args(self, used_args, args, kwargs):\r
+        pass\r
+\r
+\r
+    def format_field(self, value, format_spec):\r
+        return format(value, format_spec)\r
+\r
+\r
+    def convert_field(self, value, conversion):\r
+        # do any conversion on the resulting object\r
+        if conversion is None:\r
+            return value\r
+        elif conversion == 's':\r
+            return str(value)\r
+        elif conversion == 'r':\r
+            return repr(value)\r
+        raise ValueError("Unknown conversion specifier {0!s}".format(conversion))\r
+\r
+\r
+    # returns an iterable that contains tuples of the form:\r
+    # (literal_text, field_name, format_spec, conversion)\r
+    # literal_text can be zero length\r
+    # field_name can be None, in which case there's no\r
+    #  object to format and output\r
+    # if field_name is not None, it is looked up, formatted\r
+    #  with format_spec and conversion and then used\r
+    def parse(self, format_string):\r
+        return format_string._formatter_parser()\r
+\r
+\r
+    # given a field_name, find the object it references.\r
+    #  field_name:   the field being looked up, e.g. "0.name"\r
+    #                 or "lookup[3]"\r
+    #  used_args:    a set of which args have been used\r
+    #  args, kwargs: as passed in to vformat\r
+    def get_field(self, field_name, args, kwargs):\r
+        first, rest = field_name._formatter_field_name_split()\r
+\r
+        obj = self.get_value(first, args, kwargs)\r
+\r
+        # loop through the rest of the field_name, doing\r
+        #  getattr or getitem as needed\r
+        for is_attr, i in rest:\r
+            if is_attr:\r
+                obj = getattr(obj, i)\r
+            else:\r
+                obj = obj[i]\r
+\r
+        return obj, first\r