"""A collection of string operations (most are no longer used).
Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself.
whitespace -- a string containing all characters considered whitespace
lowercase -- a string containing all characters considered lowercase letters
uppercase -- a string containing all characters considered uppercase letters
letters -- a string containing all characters considered letters
digits -- a string containing all characters considered decimal digits
hexdigits -- a string containing all characters considered hexadecimal digits
octdigits -- a string containing all characters considered octal digits
punctuation -- a string containing all characters considered punctuation
printable -- a string containing all characters considered printable
# Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
letters = lowercase + uppercase
ascii_lowercase = lowercase
ascii_uppercase = uppercase
ascii_letters = ascii_lowercase + ascii_uppercase
hexdigits = digits + 'abcdef' + 'ABCDEF'
punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + letters + punctuation + whitespace
# Case conversion helpers
# Use str to convert Unicode literal in case of -U
l = map(chr, xrange(256))
# Functions which aren't available as string methods.
# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
def capwords(s, sep=None):
"""capwords(s [,sep]) -> string
Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. If the optional second argument sep is absent or None,
runs of whitespace characters are replaced by a single space
and leading and trailing whitespace are removed, otherwise
sep is used to split and join the words.
return (sep or ' ').join(x.capitalize() for x in s.split(sep))
# Construct a translation string
def maketrans(fromstr, tostr):
"""maketrans(frm, to) -> string
Return a translation table (a string of 256 bytes long)
suitable for use in string.translate. The strings frm and to
must be of the same length.
if len(fromstr) != len(tostr):
raise ValueError, "maketrans arguments must have same length"
fromstr = map(ord, fromstr)
for i in range(len(fromstr)):
####################################################################
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
def __init__(self, primary, secondary):
self._secondary = secondary
def __getitem__(self, key):
return self._primary[key]
return self._secondary[key]
class _TemplateMetaclass(type):
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
# Search for $$, $identifier, ${identifier}, and any bare $'s
lines = self.template[:i].splitlines(True)
colno = i - len(''.join(lines[:-1]))
raise ValueError('Invalid placeholder in string: line %d, col %d' %
def substitute(*args, **kws):
raise TypeError("descriptor 'substitute' of 'Template' object "
self, args = args[0], args[1:] # allow the "self" keyword be passed
raise TypeError('Too many positional arguments')
mapping = _multimap(kws, args[0])
# Helper function for .sub()
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
if mo.group('escaped') is not None:
if mo.group('invalid') is not None:
raise ValueError('Unrecognized named group in pattern',
return self.pattern.sub(convert, self.template)
def safe_substitute(*args, **kws):
raise TypeError("descriptor 'safe_substitute' of 'Template' object "
self, args = args[0], args[1:] # allow the "self" keyword be passed
raise TypeError('Too many positional arguments')
mapping = _multimap(kws, args[0])
# Helper function for .sub()
named = mo.group('named') or mo.group('braced')
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % (mapping[named],)
if mo.group('escaped') is not None:
if mo.group('invalid') is not None:
raise ValueError('Unrecognized named group in pattern',
return self.pattern.sub(convert, self.template)
####################################################################
# NOTE: Everything below here is deprecated. Use string methods instead.
# This stuff will go away in Python 3.0.
# Backward compatible names for exceptions
# convert UPPER CASE letters to lower case
Return a copy of the string s converted to lowercase.
# Convert lower case letters to UPPER CASE
Return a copy of the string s converted to uppercase.
# Swap lower case letters and UPPER CASE
Return a copy of the string s with upper case characters
converted to lowercase and vice versa.
# Strip leading and trailing tabs and spaces
def strip(s, chars=None):
"""strip(s [,chars]) -> string
Return a copy of the string s with leading and trailing
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping.
# Strip leading tabs and spaces
def lstrip(s, chars=None):
"""lstrip(s [,chars]) -> string
Return a copy of the string s with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
# Strip trailing tabs and spaces
def rstrip(s, chars=None):
"""rstrip(s [,chars]) -> string
Return a copy of the string s with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
# Split a string into a list of space/tab-separated words
def split(s, sep=None, maxsplit=-1):
"""split(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is given, splits at no more than
maxsplit places (resulting in at most maxsplit+1 words). If sep
is not specified or is None, any whitespace string is a separator.
(split and splitfields are synonymous)
return s.split(sep, maxsplit)
# Split a string into a list of space/tab-separated words
def rsplit(s, sep=None, maxsplit=-1):
"""rsplit(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
return s.rsplit(sep, maxsplit)
# Join fields with optional separator
def join(words, sep = ' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
(joinfields and join are synonymous)
# Find substring, raise exception if not found
"""index(s, sub [,start [,end]]) -> int
Like find but raises ValueError when the substring is not found.
# Find last substring, raise exception if not found
"""rindex(s, sub [,start [,end]]) -> int
Like rfind but raises ValueError when the substring is not found.
# Count non-overlapping occurrences of substring
"""count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
# Find substring, return -1 if not found
"""find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
# Find last substring, return -1 if not found
"""rfind(s, sub [,start [,end]]) -> int
Return the highest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
# Convert string to float
Return the floating point number represented by the string s.
# Convert string to integer
"""atoi(s [,base]) -> int
Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
# Convert string to long integer
"""atol(s [,base]) -> long
Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it is chosen from the leading characters of s, 0 for
octal, 0x or 0X for hexadecimal. If base is 16, a preceding
0x or 0X is accepted. A trailing L or l is not accepted,
def ljust(s, width, *args):
"""ljust(s, width[, fillchar]) -> string
Return a left-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
return s.ljust(width, *args)
def rjust(s, width, *args):
"""rjust(s, width[, fillchar]) -> string
Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
return s.rjust(width, *args)
def center(s, width, *args):
"""center(s, width[, fillchar]) -> string
Return a center version of s, in a field of the specified
width. padded with spaces as needed. The string is never
truncated. If specified the fillchar is used instead of spaces.
return s.center(width, *args)
# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
# Decadent feature: the argument may be a string or a number
# (Use of this is deprecated; it should be a string as with ljust c.s.)
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
if not isinstance(x, basestring):
# Expand tabs in a string.
# Doesn't take non-printing chars into account, but does understand \n.
def expandtabs(s, tabsize=8):
"""expandtabs(s [,tabsize]) -> string
Return a copy of the string s with all tab characters replaced
by the appropriate number of spaces, depending on the current
column, and the tabsize (default 8).
return s.expandtabs(tabsize)
# Character translation through look-up table.
def translate(s, table, deletions=""):
"""translate(s,table [,deletions]) -> string
Return a copy of the string s, where all characters occurring
in the optional argument deletions are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256. The
deletions argument is not allowed for Unicode strings.
if deletions or table is None:
return s.translate(table, deletions)
# Add s[:0] so that if s is Unicode and table is an 8-bit string,
# table is converted to Unicode. This means that table *cannot*
# be a dictionary -- for that feature, use u.translate() directly.
return s.translate(table + s[:0])