home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_Lib_string.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  11.1 KB  |  382 lines

  1. """A collection of string operations (most are no longer used in Python 1.6).
  2.  
  3. Warning: most of the code you see here isn't normally used nowadays.  With
  4. Python 1.6, many of these functions are implemented as methods on the
  5. standard string object. They used to be implemented by a built-in module
  6. called strop, but strop is now obsolete itself.
  7.  
  8. Public module variables:
  9.  
  10. whitespace -- a string containing all characters considered whitespace
  11. lowercase -- a string containing all characters considered lowercase letters
  12. uppercase -- a string containing all characters considered uppercase letters
  13. letters -- a string containing all characters considered letters
  14. digits -- a string containing all characters considered decimal digits
  15. hexdigits -- a string containing all characters considered hexadecimal digits
  16. octdigits -- a string containing all characters considered octal digits
  17. punctuation -- a string containing all characters considered punctuation
  18. printable -- a string containing all characters considered printable
  19.  
  20. """
  21.  
  22. # Some strings for ctype-style character classification
  23. whitespace = ' \t\n\r\v\f'
  24. lowercase = 'abcdefghijklmnopqrstuvwxyz'
  25. uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  26. letters = lowercase + uppercase
  27. digits = '0123456789'
  28. hexdigits = digits + 'abcdef' + 'ABCDEF'
  29. octdigits = '01234567'
  30. punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
  31. printable = digits + letters + punctuation + whitespace
  32.  
  33. # Case conversion helpers
  34. _idmap = ''
  35. for i in range(256): _idmap = _idmap + chr(i)
  36. del i
  37.  
  38. # Backward compatible names for exceptions
  39. index_error = ValueError
  40. atoi_error = ValueError
  41. atof_error = ValueError
  42. atol_error = ValueError
  43.  
  44. # convert UPPER CASE letters to lower case
  45. def lower(s):
  46.     """lower(s) -> string
  47.  
  48.     Return a copy of the string s converted to lowercase.
  49.  
  50.     """
  51.     return s.lower()
  52.  
  53. # Convert lower case letters to UPPER CASE
  54. def upper(s):
  55.     """upper(s) -> string
  56.  
  57.     Return a copy of the string s converted to uppercase.
  58.  
  59.     """
  60.     return s.upper()
  61.  
  62. # Swap lower case letters and UPPER CASE
  63. def swapcase(s):
  64.     """swapcase(s) -> string
  65.  
  66.     Return a copy of the string s with upper case characters
  67.     converted to lowercase and vice versa.
  68.  
  69.     """
  70.     return s.swapcase()
  71.  
  72. # Strip leading and trailing tabs and spaces
  73. def strip(s):
  74.     """strip(s) -> string
  75.  
  76.     Return a copy of the string s with leading and trailing
  77.     whitespace removed.
  78.  
  79.     """
  80.     return s.strip()
  81.  
  82. # Strip leading tabs and spaces
  83. def lstrip(s):
  84.     """lstrip(s) -> string
  85.  
  86.     Return a copy of the string s with leading whitespace removed.
  87.  
  88.     """
  89.     return s.lstrip()
  90.  
  91. # Strip trailing tabs and spaces
  92. def rstrip(s):
  93.     """rstrip(s) -> string
  94.  
  95.     Return a copy of the string s with trailing whitespace
  96.     removed.
  97.  
  98.     """
  99.     return s.rstrip()
  100.  
  101.  
  102. # Split a string into a list of space/tab-separated words
  103. def split(s, sep=None, maxsplit=-1):
  104.     """split(s [,sep [,maxsplit]]) -> list of strings
  105.  
  106.     Return a list of the words in the string s, using sep as the
  107.     delimiter string.  If maxsplit is given, splits into at most
  108.     maxsplit words.  If sep is not specified, any whitespace string
  109.     is a separator.
  110.  
  111.     (split and splitfields are synonymous)
  112.  
  113.     """
  114.     return s.split(sep, maxsplit)
  115. splitfields = split
  116.  
  117. # Join fields with optional separator
  118. def join(words, sep = ' '):
  119.     """join(list [,sep]) -> string
  120.  
  121.     Return a string composed of the words in list, with
  122.     intervening occurrences of sep.  The default separator is a
  123.     single space.
  124.  
  125.     (joinfields and join are synonymous)
  126.  
  127.     """
  128.     return sep.join(words)
  129. joinfields = join
  130.  
  131. # Find substring, raise exception if not found
  132. def index(s, *args):
  133.     """index(s, sub [,start [,end]]) -> int
  134.  
  135.     Like find but raises ValueError when the substring is not found.
  136.  
  137.     """
  138.     return s.index(*args)
  139.  
  140. # Find last substring, raise exception if not found
  141. def rindex(s, *args):
  142.     """rindex(s, sub [,start [,end]]) -> int
  143.  
  144.     Like rfind but raises ValueError when the substring is not found.
  145.  
  146.     """
  147.     return s.rindex(*args)
  148.  
  149. # Count non-overlapping occurrences of substring
  150. def count(s, *args):
  151.     """count(s, sub[, start[,end]]) -> int
  152.  
  153.     Return the number of occurrences of substring sub in string
  154.     s[start:end].  Optional arguments start and end are
  155.     interpreted as in slice notation.
  156.  
  157.     """
  158.     return s.count(*args)
  159.  
  160. # Find substring, return -1 if not found
  161. def find(s, *args):
  162.     """find(s, sub [,start [,end]]) -> in
  163.  
  164.     Return the lowest index in s where substring sub is found,
  165.     such that sub is contained within s[start,end].  Optional
  166.     arguments start and end are interpreted as in slice notation.
  167.  
  168.     Return -1 on failure.
  169.  
  170.     """
  171.     return s.find(*args)
  172.  
  173. # Find last substring, return -1 if not found
  174. def rfind(s, *args):
  175.     """rfind(s, sub [,start [,end]]) -> int
  176.  
  177.     Return the highest index in s where substring sub is found,
  178.     such that sub is contained within s[start,end].  Optional
  179.     arguments start and end are interpreted as in slice notation.
  180.  
  181.     Return -1 on failure.
  182.  
  183.     """
  184.     return s.rfind(*args)
  185.  
  186. # for a bit of speed
  187. _float = float
  188. _int = int
  189. _long = long
  190. _StringType = type('')
  191.  
  192. # Convert string to float
  193. def atof(s):
  194.     """atof(s) -> float
  195.  
  196.     Return the floating point number represented by the string s.
  197.  
  198.     """
  199.     return _float(s)
  200.  
  201.  
  202. # Convert string to integer
  203. def atoi(s , base=10):
  204.     """atoi(s [,base]) -> int
  205.  
  206.     Return the integer represented by the string s in the given
  207.     base, which defaults to 10.  The string s must consist of one
  208.     or more digits, possibly preceded by a sign.  If base is 0, it
  209.     is chosen from the leading characters of s, 0 for octal, 0x or
  210.     0X for hexadecimal.  If base is 16, a preceding 0x or 0X is
  211.     accepted.
  212.  
  213.     """
  214.     return _int(s, base)
  215.  
  216.  
  217. # Convert string to long integer
  218. def atol(s, base=10):
  219.     """atol(s [,base]) -> long
  220.  
  221.     Return the long integer represented by the string s in the
  222.     given base, which defaults to 10.  The string s must consist
  223.     of one or more digits, possibly preceded by a sign.  If base
  224.     is 0, it is chosen from the leading characters of s, 0 for
  225.     octal, 0x or 0X for hexadecimal.  If base is 16, a preceding
  226.     0x or 0X is accepted.  A trailing L or l is not accepted,
  227.     unless base is 0.
  228.  
  229.     """
  230.     return _long(s, base)
  231.  
  232.  
  233. # Left-justify a string
  234. def ljust(s, width):
  235.     """ljust(s, width) -> string
  236.  
  237.     Return a left-justified version of s, in a field of the
  238.     specified width, padded with spaces as needed.  The string is
  239.     never truncated.
  240.  
  241.     """
  242.     return s.ljust(width)
  243.  
  244. # Right-justify a string
  245. def rjust(s, width):
  246.     """rjust(s, width) -> string
  247.  
  248.     Return a right-justified version of s, in a field of the
  249.     specified width, padded with spaces as needed.  The string is
  250.     never truncated.
  251.  
  252.     """
  253.     return s.rjust(width)
  254.  
  255. # Center a string
  256. def center(s, width):
  257.     """center(s, width) -> string
  258.  
  259.     Return a center version of s, in a field of the specified
  260.     width. padded with spaces as needed.  The string is never
  261.     truncated.
  262.  
  263.     """
  264.     return s.center(width)
  265.  
  266. # Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
  267. # Decadent feature: the argument may be a string or a number
  268. # (Use of this is deprecated; it should be a string as with ljust c.s.)
  269. def zfill(x, width):
  270.     """zfill(x, width) -> string
  271.  
  272.     Pad a numeric string x with zeros on the left, to fill a field
  273.     of the specified width.  The string x is never truncated.
  274.  
  275.     """
  276.     if type(x) == type(''): s = x
  277.     else: s = `x`
  278.     n = len(s)
  279.     if n >= width: return s
  280.     sign = ''
  281.     if s[0] in ('-', '+'):
  282.         sign, s = s[0], s[1:]
  283.     return sign + '0'*(width-n) + s
  284.  
  285. # Expand tabs in a string.
  286. # Doesn't take non-printing chars into account, but does understand \n.
  287. def expandtabs(s, tabsize=8):
  288.     """expandtabs(s [,tabsize]) -> string
  289.  
  290.     Return a copy of the string s with all tab characters replaced
  291.     by the appropriate number of spaces, depending on the current
  292.     column, and the tabsize (default 8).
  293.  
  294.     """
  295.     return s.expandtabs(tabsize)
  296.  
  297. # Character translation through look-up table.
  298. def translate(s, table, deletions=""):
  299.     """translate(s,table [,deletions]) -> string
  300.  
  301.     Return a copy of the string s, where all characters occurring
  302.     in the optional argument deletions are removed, and the
  303.     remaining characters have been mapped through the given
  304.     translation table, which must be a string of length 256.  The
  305.     deletions argument is not allowed for Unicode strings.
  306.  
  307.     """
  308.     if deletions:
  309.         return s.translate(table, deletions)
  310.     else:
  311.         # Add s[:0] so that if s is Unicode and table is an 8-bit string,
  312.         # table is converted to Unicode.  This means that table *cannot*
  313.         # be a dictionary -- for that feature, use u.translate() directly.
  314.         return s.translate(table + s[:0])
  315.  
  316. # Capitalize a string, e.g. "aBc  dEf" -> "Abc  def".
  317. def capitalize(s):
  318.     """capitalize(s) -> string
  319.  
  320.     Return a copy of the string s with only its first character
  321.     capitalized.
  322.  
  323.     """
  324.     return s.capitalize()
  325.  
  326. # Capitalize the words in a string, e.g. " aBc  dEf " -> "Abc Def".
  327. # See also regsub.capwords().
  328. def capwords(s, sep=None):
  329.     """capwords(s, [sep]) -> string
  330.  
  331.     Split the argument into words using split, capitalize each
  332.     word using capitalize, and join the capitalized words using
  333.     join. Note that this replaces runs of whitespace characters by
  334.     a single space.
  335.  
  336.     """
  337.     return join(map(capitalize, s.split(sep)), sep or ' ')
  338.  
  339. # Construct a translation string
  340. _idmapL = None
  341. def maketrans(fromstr, tostr):
  342.     """maketrans(frm, to) -> string
  343.  
  344.     Return a translation table (a string of 256 bytes long)
  345.     suitable for use in string.translate.  The strings frm and to
  346.     must be of the same length.
  347.  
  348.     """
  349.     if len(fromstr) != len(tostr):
  350.         raise ValueError, "maketrans arguments must have same length"
  351.     global _idmapL
  352.     if not _idmapL:
  353.         _idmapL = map(None, _idmap)
  354.     L = _idmapL[:]
  355.     fromstr = map(ord, fromstr)
  356.     for i in range(len(fromstr)):
  357.         L[fromstr[i]] = tostr[i]
  358.     return join(L, "")
  359.  
  360. # Substring replacement (global)
  361. def replace(s, old, new, maxsplit=-1):
  362.     """replace (str, old, new[, maxsplit]) -> string
  363.  
  364.     Return a copy of string str with all occurrences of substring
  365.     old replaced by new. If the optional argument maxsplit is
  366.     given, only the first maxsplit occurrences are replaced.
  367.  
  368.     """
  369.     return s.replace(old, new, maxsplit)
  370.  
  371.  
  372. # Try importing optional built-in module "strop" -- if it exists,
  373. # it redefines some string operations that are 100-1000 times faster.
  374. # It also defines values for whitespace, lowercase and uppercase
  375. # that match <ctype.h>'s definitions.
  376.  
  377. try:
  378.     from strop import maketrans, lowercase, uppercase, whitespace
  379.     letters = lowercase + uppercase
  380. except ImportError:
  381.     pass                                          # Use the original versions
  382.