2003-10-03 11:05:26 -03:00
|
|
|
"""A collection of string operations (most are no longer used).
|
1990-10-13 16:23:40 -03:00
|
|
|
|
2003-10-03 11:05:26 -03:00
|
|
|
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.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
|
|
|
Public module variables:
|
|
|
|
|
|
|
|
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
|
2000-09-18 16:38:11 -03:00
|
|
|
punctuation -- a string containing all characters considered punctuation
|
|
|
|
printable -- a string containing all characters considered printable
|
1997-12-29 15:26:28 -04:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
1990-10-13 16:23:40 -03:00
|
|
|
# Some strings for ctype-style character classification
|
1993-07-29 06:37:38 -03:00
|
|
|
whitespace = ' \t\n\r\v\f'
|
1990-10-13 16:23:40 -03:00
|
|
|
lowercase = 'abcdefghijklmnopqrstuvwxyz'
|
|
|
|
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
|
|
letters = lowercase + uppercase
|
2001-07-20 15:38:26 -03:00
|
|
|
ascii_lowercase = lowercase
|
|
|
|
ascii_uppercase = uppercase
|
|
|
|
ascii_letters = ascii_lowercase + ascii_uppercase
|
1990-10-13 16:23:40 -03:00
|
|
|
digits = '0123456789'
|
|
|
|
hexdigits = digits + 'abcdef' + 'ABCDEF'
|
|
|
|
octdigits = '01234567'
|
2001-01-14 21:36:40 -04:00
|
|
|
punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
|
2000-09-18 13:46:17 -03:00
|
|
|
printable = digits + letters + punctuation + whitespace
|
1990-10-13 16:23:40 -03:00
|
|
|
|
|
|
|
# Case conversion helpers
|
2002-10-14 17:03:40 -03:00
|
|
|
# Use str to convert Unicode literal in case of -U
|
|
|
|
l = map(chr, xrange(256))
|
|
|
|
_idmap = str('').join(l)
|
|
|
|
del l
|
1990-10-13 16:23:40 -03:00
|
|
|
|
2004-08-24 23:22:30 -03:00
|
|
|
# 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):
|
2009-09-26 08:20:53 -03:00
|
|
|
"""capwords(s [,sep]) -> string
|
2004-08-24 23:22:30 -03:00
|
|
|
|
|
|
|
Split the argument into words using split, capitalize each
|
|
|
|
word using capitalize, and join the capitalized words using
|
2009-09-26 08:20:53 -03:00
|
|
|
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.
|
2004-08-24 23:22:30 -03:00
|
|
|
|
|
|
|
"""
|
2009-09-26 08:20:53 -03:00
|
|
|
return (sep or ' ').join(x.capitalize() for x in s.split(sep))
|
2004-08-24 23:22:30 -03:00
|
|
|
|
|
|
|
|
|
|
|
# Construct a translation string
|
|
|
|
_idmapL = None
|
|
|
|
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"
|
|
|
|
global _idmapL
|
|
|
|
if not _idmapL:
|
2008-07-18 16:06:13 -03:00
|
|
|
_idmapL = list(_idmap)
|
2004-08-24 23:22:30 -03:00
|
|
|
L = _idmapL[:]
|
|
|
|
fromstr = map(ord, fromstr)
|
|
|
|
for i in range(len(fromstr)):
|
|
|
|
L[fromstr[i]] = tostr[i]
|
|
|
|
return ''.join(L)
|
|
|
|
|
|
|
|
|
2004-12-07 03:55:07 -04:00
|
|
|
|
2004-08-25 21:21:13 -03:00
|
|
|
####################################################################
|
2004-08-24 23:22:30 -03:00
|
|
|
import re as _re
|
|
|
|
|
2004-09-13 11:35:04 -03:00
|
|
|
class _multimap:
|
|
|
|
"""Helper class for combining multiple mappings.
|
|
|
|
|
|
|
|
Used by .{safe_,}substitute() to combine the mapping and keyword
|
|
|
|
arguments.
|
|
|
|
"""
|
|
|
|
def __init__(self, primary, secondary):
|
|
|
|
self._primary = primary
|
|
|
|
self._secondary = secondary
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
try:
|
|
|
|
return self._primary[key]
|
|
|
|
except KeyError:
|
|
|
|
return self._secondary[key]
|
|
|
|
|
|
|
|
|
2004-09-10 00:08:08 -03:00
|
|
|
class _TemplateMetaclass(type):
|
|
|
|
pattern = r"""
|
2004-09-26 15:56:44 -03:00
|
|
|
%(delim)s(?:
|
|
|
|
(?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
|
|
|
|
)
|
2004-09-10 00:08:08 -03:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(cls, name, bases, dct):
|
2007-03-23 15:53:03 -03:00
|
|
|
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
|
2004-09-10 00:08:08 -03:00
|
|
|
if 'pattern' in dct:
|
|
|
|
pattern = cls.pattern
|
|
|
|
else:
|
|
|
|
pattern = _TemplateMetaclass.pattern % {
|
2004-09-17 21:06:34 -03:00
|
|
|
'delim' : _re.escape(cls.delimiter),
|
2004-09-10 00:08:08 -03:00
|
|
|
'id' : cls.idpattern,
|
|
|
|
}
|
|
|
|
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
|
|
|
|
|
|
|
|
|
|
|
|
class Template:
|
2004-08-24 23:22:30 -03:00
|
|
|
"""A string class for supporting $-substitutions."""
|
2004-09-10 00:08:08 -03:00
|
|
|
__metaclass__ = _TemplateMetaclass
|
|
|
|
|
2004-09-17 21:06:34 -03:00
|
|
|
delimiter = '$'
|
2004-09-10 00:08:08 -03:00
|
|
|
idpattern = r'[_a-z][_a-z0-9]*'
|
|
|
|
|
|
|
|
def __init__(self, template):
|
|
|
|
self.template = template
|
2004-08-24 23:22:30 -03:00
|
|
|
|
|
|
|
# Search for $$, $identifier, ${identifier}, and any bare $'s
|
2004-09-10 00:08:08 -03:00
|
|
|
|
2004-09-13 17:52:50 -03:00
|
|
|
def _invalid(self, mo):
|
|
|
|
i = mo.start('invalid')
|
2004-09-10 00:08:08 -03:00
|
|
|
lines = self.template[:i].splitlines(True)
|
|
|
|
if not lines:
|
|
|
|
colno = 1
|
|
|
|
lineno = 1
|
|
|
|
else:
|
|
|
|
colno = i - len(''.join(lines[:-1]))
|
|
|
|
lineno = len(lines)
|
|
|
|
raise ValueError('Invalid placeholder in string: line %d, col %d' %
|
|
|
|
(lineno, colno))
|
|
|
|
|
2004-09-13 12:25:15 -03:00
|
|
|
def substitute(self, *args, **kws):
|
|
|
|
if len(args) > 1:
|
|
|
|
raise TypeError('Too many positional arguments')
|
|
|
|
if not args:
|
|
|
|
mapping = kws
|
2004-09-13 11:35:04 -03:00
|
|
|
elif kws:
|
2004-09-13 12:25:15 -03:00
|
|
|
mapping = _multimap(kws, args[0])
|
|
|
|
else:
|
|
|
|
mapping = args[0]
|
2004-09-13 11:35:04 -03:00
|
|
|
# Helper function for .sub()
|
2004-08-24 23:22:30 -03:00
|
|
|
def convert(mo):
|
2004-09-13 17:52:50 -03:00
|
|
|
# Check the most common path first.
|
|
|
|
named = mo.group('named') or mo.group('braced')
|
|
|
|
if named is not None:
|
|
|
|
val = mapping[named]
|
|
|
|
# We use this idiom instead of str() because the latter will
|
|
|
|
# fail if val is a Unicode containing non-ASCII characters.
|
2006-07-05 08:03:49 -03:00
|
|
|
return '%s' % (val,)
|
2004-08-25 21:21:13 -03:00
|
|
|
if mo.group('escaped') is not None:
|
2004-09-17 21:06:34 -03:00
|
|
|
return self.delimiter
|
2004-09-13 17:52:50 -03:00
|
|
|
if mo.group('invalid') is not None:
|
|
|
|
self._invalid(mo)
|
2004-10-17 13:27:18 -03:00
|
|
|
raise ValueError('Unrecognized named group in pattern',
|
|
|
|
self.pattern)
|
2004-09-10 00:08:08 -03:00
|
|
|
return self.pattern.sub(convert, self.template)
|
2004-08-24 23:22:30 -03:00
|
|
|
|
2004-09-13 12:25:15 -03:00
|
|
|
def safe_substitute(self, *args, **kws):
|
|
|
|
if len(args) > 1:
|
|
|
|
raise TypeError('Too many positional arguments')
|
|
|
|
if not args:
|
|
|
|
mapping = kws
|
2004-09-13 11:35:04 -03:00
|
|
|
elif kws:
|
2004-09-13 12:25:15 -03:00
|
|
|
mapping = _multimap(kws, args[0])
|
|
|
|
else:
|
|
|
|
mapping = args[0]
|
2004-09-13 11:35:04 -03:00
|
|
|
# Helper function for .sub()
|
2004-08-24 23:22:30 -03:00
|
|
|
def convert(mo):
|
2004-08-25 21:21:13 -03:00
|
|
|
named = mo.group('named')
|
2004-08-24 23:22:30 -03:00
|
|
|
if named is not None:
|
|
|
|
try:
|
2004-09-10 00:08:08 -03:00
|
|
|
# We use this idiom instead of str() because the latter
|
|
|
|
# will fail if val is a Unicode containing non-ASCII
|
2006-07-05 08:03:49 -03:00
|
|
|
return '%s' % (mapping[named],)
|
2004-08-24 23:22:30 -03:00
|
|
|
except KeyError:
|
2004-09-17 21:06:34 -03:00
|
|
|
return self.delimiter + named
|
2004-08-25 21:21:13 -03:00
|
|
|
braced = mo.group('braced')
|
2004-09-13 23:34:08 -03:00
|
|
|
if braced is not None:
|
|
|
|
try:
|
2006-07-05 08:03:49 -03:00
|
|
|
return '%s' % (mapping[braced],)
|
2004-09-13 23:34:08 -03:00
|
|
|
except KeyError:
|
2004-09-17 21:06:34 -03:00
|
|
|
return self.delimiter + '{' + braced + '}'
|
2004-09-13 17:52:50 -03:00
|
|
|
if mo.group('escaped') is not None:
|
2004-09-17 21:06:34 -03:00
|
|
|
return self.delimiter
|
2004-09-13 17:52:50 -03:00
|
|
|
if mo.group('invalid') is not None:
|
2004-10-31 23:52:43 -04:00
|
|
|
return self.delimiter
|
2004-10-17 13:27:18 -03:00
|
|
|
raise ValueError('Unrecognized named group in pattern',
|
|
|
|
self.pattern)
|
2004-09-10 00:08:08 -03:00
|
|
|
return self.pattern.sub(convert, self.template)
|
2004-08-24 23:22:30 -03:00
|
|
|
|
|
|
|
|
2004-12-07 03:55:07 -04:00
|
|
|
|
2004-08-25 21:21:13 -03:00
|
|
|
####################################################################
|
2004-08-24 23:22:30 -03:00
|
|
|
# NOTE: Everything below here is deprecated. Use string methods instead.
|
|
|
|
# This stuff will go away in Python 3.0.
|
|
|
|
|
1994-08-17 10:16:11 -03:00
|
|
|
# Backward compatible names for exceptions
|
|
|
|
index_error = ValueError
|
|
|
|
atoi_error = ValueError
|
|
|
|
atof_error = ValueError
|
|
|
|
atol_error = ValueError
|
|
|
|
|
1990-10-13 16:23:40 -03:00
|
|
|
# convert UPPER CASE letters to lower case
|
|
|
|
def lower(s):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""lower(s) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a copy of the string s converted to lowercase.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
|
|
|
return s.lower()
|
1990-10-13 16:23:40 -03:00
|
|
|
|
|
|
|
# Convert lower case letters to UPPER CASE
|
|
|
|
def upper(s):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""upper(s) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a copy of the string s converted to uppercase.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
|
|
|
return s.upper()
|
1990-10-13 16:23:40 -03:00
|
|
|
|
|
|
|
# Swap lower case letters and UPPER CASE
|
|
|
|
def swapcase(s):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""swapcase(s) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a copy of the string s with upper case characters
|
|
|
|
converted to lowercase and vice versa.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
|
|
|
return s.swapcase()
|
1990-10-13 16:23:40 -03:00
|
|
|
|
|
|
|
# Strip leading and trailing tabs and spaces
|
2002-11-08 08:09:59 -04:00
|
|
|
def strip(s, chars=None):
|
2002-11-13 23:31:32 -04:00
|
|
|
"""strip(s [,chars]) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a copy of the string s with leading and trailing
|
|
|
|
whitespace removed.
|
2003-04-10 19:35:32 -03:00
|
|
|
If chars is given and not None, remove characters in chars instead.
|
2002-11-13 23:31:32 -04:00
|
|
|
If chars is unicode, S will be converted to unicode before stripping.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
2002-11-08 08:09:59 -04:00
|
|
|
return s.strip(chars)
|
1990-10-13 16:23:40 -03:00
|
|
|
|
Add optional third parameter to split() and splitfields(), giving the
maximum number of delimiters to parse; e.g.
splitfields("a,b,c,d", ",", 2) -> ["a", "b", "c,d"].
1996-08-08 15:40:59 -03:00
|
|
|
# Strip leading tabs and spaces
|
2003-04-10 19:35:32 -03:00
|
|
|
def lstrip(s, chars=None):
|
|
|
|
"""lstrip(s [,chars]) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a copy of the string s with leading whitespace removed.
|
2003-04-10 19:35:32 -03:00
|
|
|
If chars is given and not None, remove characters in chars instead.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
2003-04-10 19:35:32 -03:00
|
|
|
return s.lstrip(chars)
|
Add optional third parameter to split() and splitfields(), giving the
maximum number of delimiters to parse; e.g.
splitfields("a,b,c,d", ",", 2) -> ["a", "b", "c,d"].
1996-08-08 15:40:59 -03:00
|
|
|
|
|
|
|
# Strip trailing tabs and spaces
|
2003-04-10 19:35:32 -03:00
|
|
|
def rstrip(s, chars=None):
|
|
|
|
"""rstrip(s [,chars]) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
2003-04-10 19:35:32 -03:00
|
|
|
Return a copy of the string s with trailing whitespace removed.
|
|
|
|
If chars is given and not None, remove characters in chars instead.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
2003-04-10 19:35:32 -03:00
|
|
|
return s.rstrip(chars)
|
Add optional third parameter to split() and splitfields(), giving the
maximum number of delimiters to parse; e.g.
splitfields("a,b,c,d", ",", 2) -> ["a", "b", "c,d"].
1996-08-08 15:40:59 -03:00
|
|
|
|
|
|
|
|
1990-10-13 16:23:40 -03:00
|
|
|
# Split a string into a list of space/tab-separated words
|
2000-03-10 19:22:10 -04:00
|
|
|
def split(s, sep=None, maxsplit=-1):
|
1999-11-04 15:19:48 -04:00
|
|
|
"""split(s [,sep [,maxsplit]]) -> list of strings
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a list of the words in the string s, using sep as the
|
2002-01-30 12:15:13 -04:00
|
|
|
delimiter string. If maxsplit is given, splits at no more than
|
|
|
|
maxsplit places (resulting in at most maxsplit+1 words). If sep
|
2004-09-14 06:45:10 -03:00
|
|
|
is not specified or is None, any whitespace string is a separator.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
(split and splitfields are synonymous)
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
|
|
|
return s.split(sep, maxsplit)
|
|
|
|
splitfields = split
|
1991-04-07 10:42:19 -03:00
|
|
|
|
2003-12-15 14:49:53 -04:00
|
|
|
# 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
|
|
|
|
is a separator.
|
|
|
|
"""
|
|
|
|
return s.rsplit(sep, maxsplit)
|
|
|
|
|
1995-06-22 15:58:00 -03:00
|
|
|
# Join fields with optional separator
|
1999-10-12 16:54:53 -03:00
|
|
|
def join(words, sep = ' '):
|
|
|
|
"""join(list [,sep]) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a string composed of the words in list, with
|
2000-07-16 09:04:32 -03:00
|
|
|
intervening occurrences of sep. The default separator is a
|
1999-10-12 16:54:53 -03:00
|
|
|
single space.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
(joinfields and join are synonymous)
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
|
|
|
return sep.join(words)
|
|
|
|
joinfields = join
|
1991-04-07 10:42:19 -03:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
# Find substring, raise exception if not found
|
|
|
|
def index(s, *args):
|
|
|
|
"""index(s, sub [,start [,end]]) -> int
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Like find but raises ValueError when the substring is not found.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
2000-07-03 04:23:13 -03:00
|
|
|
return s.index(*args)
|
1993-05-24 11:16:22 -03:00
|
|
|
|
* string.py: added rindex(), rfind(); changed index() to interpret
negative start indices starting from the right.
* ftplib.py: debug() -> set_debuglevel(); change demo to use __init__().
* os.py: added execl, execlp, and execvp.
* lambda.py: removed (now that we have built-in map, reduce, bagof, lambda)
* test_b{1,2}.py, testall.out: added tests for bagof, lambda, map, reduce
* commands.py: use os, not posix
* test_grammar.py: make it easy to disable non-portable int overflow tests
* dis.py: don't abuse range()
1993-11-08 11:05:21 -04:00
|
|
|
# Find last substring, raise exception if not found
|
1999-10-12 16:54:53 -03:00
|
|
|
def rindex(s, *args):
|
|
|
|
"""rindex(s, sub [,start [,end]]) -> int
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Like rfind but raises ValueError when the substring is not found.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
2000-07-03 04:23:13 -03:00
|
|
|
return s.rindex(*args)
|
1994-08-01 08:34:53 -03:00
|
|
|
|
|
|
|
# Count non-overlapping occurrences of substring
|
1999-10-12 16:54:53 -03:00
|
|
|
def count(s, *args):
|
|
|
|
"""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.
|
|
|
|
|
|
|
|
"""
|
2000-07-03 04:23:13 -03:00
|
|
|
return s.count(*args)
|
* string.py: added rindex(), rfind(); changed index() to interpret
negative start indices starting from the right.
* ftplib.py: debug() -> set_debuglevel(); change demo to use __init__().
* os.py: added execl, execlp, and execvp.
* lambda.py: removed (now that we have built-in map, reduce, bagof, lambda)
* test_b{1,2}.py, testall.out: added tests for bagof, lambda, map, reduce
* commands.py: use os, not posix
* test_grammar.py: make it easy to disable non-portable int overflow tests
* dis.py: don't abuse range()
1993-11-08 11:05:21 -04:00
|
|
|
|
1993-05-24 11:16:22 -03:00
|
|
|
# Find substring, return -1 if not found
|
1999-10-12 16:54:53 -03:00
|
|
|
def find(s, *args):
|
|
|
|
"""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.
|
|
|
|
|
|
|
|
Return -1 on failure.
|
|
|
|
|
|
|
|
"""
|
2000-07-03 04:23:13 -03:00
|
|
|
return s.find(*args)
|
1990-10-13 16:23:40 -03:00
|
|
|
|
* string.py: added rindex(), rfind(); changed index() to interpret
negative start indices starting from the right.
* ftplib.py: debug() -> set_debuglevel(); change demo to use __init__().
* os.py: added execl, execlp, and execvp.
* lambda.py: removed (now that we have built-in map, reduce, bagof, lambda)
* test_b{1,2}.py, testall.out: added tests for bagof, lambda, map, reduce
* commands.py: use os, not posix
* test_grammar.py: make it easy to disable non-portable int overflow tests
* dis.py: don't abuse range()
1993-11-08 11:05:21 -04:00
|
|
|
# Find last substring, return -1 if not found
|
1999-10-12 16:54:53 -03:00
|
|
|
def rfind(s, *args):
|
|
|
|
"""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.
|
|
|
|
|
|
|
|
Return -1 on failure.
|
|
|
|
|
|
|
|
"""
|
2000-07-03 04:23:13 -03:00
|
|
|
return s.rfind(*args)
|
1999-10-12 16:54:53 -03:00
|
|
|
|
|
|
|
# for a bit of speed
|
|
|
|
_float = float
|
|
|
|
_int = int
|
|
|
|
_long = long
|
1997-12-10 18:59:55 -04:00
|
|
|
|
1993-10-22 10:56:35 -03:00
|
|
|
# Convert string to float
|
1999-10-12 16:54:53 -03:00
|
|
|
def atof(s):
|
|
|
|
"""atof(s) -> float
|
|
|
|
|
|
|
|
Return the floating point number represented by the string s.
|
|
|
|
|
|
|
|
"""
|
2000-04-05 17:11:21 -03:00
|
|
|
return _float(s)
|
|
|
|
|
1993-10-22 10:56:35 -03:00
|
|
|
|
1990-10-13 16:23:40 -03:00
|
|
|
# Convert string to integer
|
2000-04-05 17:11:21 -03:00
|
|
|
def atoi(s , base=10):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""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
|
|
|
|
accepted.
|
|
|
|
|
|
|
|
"""
|
2000-04-05 17:11:21 -03:00
|
|
|
return _int(s, base)
|
1999-10-12 16:54:53 -03:00
|
|
|
|
1990-10-13 16:23:40 -03:00
|
|
|
|
1993-10-22 10:56:35 -03:00
|
|
|
# Convert string to long integer
|
2000-04-05 17:11:21 -03:00
|
|
|
def atol(s, base=10):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""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,
|
|
|
|
unless base is 0.
|
|
|
|
|
|
|
|
"""
|
2000-04-05 17:11:21 -03:00
|
|
|
return _long(s, base)
|
1999-10-12 16:54:53 -03:00
|
|
|
|
1993-10-22 10:56:35 -03:00
|
|
|
|
1990-10-13 16:23:40 -03:00
|
|
|
# Left-justify a string
|
2003-11-26 04:21:35 -04:00
|
|
|
def ljust(s, width, *args):
|
|
|
|
"""ljust(s, width[, fillchar]) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a left-justified version of s, in a field of the
|
|
|
|
specified width, padded with spaces as needed. The string is
|
2003-11-26 04:21:35 -04:00
|
|
|
never truncated. If specified the fillchar is used instead of spaces.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
2003-11-26 04:21:35 -04:00
|
|
|
return s.ljust(width, *args)
|
1990-10-13 16:23:40 -03:00
|
|
|
|
|
|
|
# Right-justify a string
|
2003-11-26 04:21:35 -04:00
|
|
|
def rjust(s, width, *args):
|
|
|
|
"""rjust(s, width[, fillchar]) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a right-justified version of s, in a field of the
|
|
|
|
specified width, padded with spaces as needed. The string is
|
2003-11-26 04:21:35 -04:00
|
|
|
never truncated. If specified the fillchar is used instead of spaces.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
2003-11-26 04:21:35 -04:00
|
|
|
return s.rjust(width, *args)
|
1990-10-13 16:23:40 -03:00
|
|
|
|
|
|
|
# Center a string
|
2003-11-26 04:21:35 -04:00
|
|
|
def center(s, width, *args):
|
|
|
|
"""center(s, width[, fillchar]) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a center version of s, in a field of the specified
|
|
|
|
width. padded with spaces as needed. The string is never
|
2003-11-26 04:21:35 -04:00
|
|
|
truncated. If specified the fillchar is used instead of spaces.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
2003-11-26 04:21:35 -04:00
|
|
|
return s.center(width, *args)
|
1990-10-13 16:23:40 -03:00
|
|
|
|
|
|
|
# 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.)
|
|
|
|
def zfill(x, width):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""zfill(x, width) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Pad a numeric string x with zeros on the left, to fill a field
|
|
|
|
of the specified width. The string x is never truncated.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
Remove uses of the string and types modules:
x in string.whitespace => x.isspace()
type(x) in types.StringTypes => isinstance(x, basestring)
isinstance(x, types.StringTypes) => isinstance(x, basestring)
type(x) is types.StringType => isinstance(x, str)
type(x) == types.StringType => isinstance(x, str)
string.split(x, ...) => x.split(...)
string.join(x, y) => y.join(x)
string.zfill(x, ...) => x.zfill(...)
string.count(x, ...) => x.count(...)
hasattr(types, "UnicodeType") => try: unicode except NameError:
type(x) != types.TupleTuple => not isinstance(x, tuple)
isinstance(x, types.TupleType) => isinstance(x, tuple)
type(x) is types.IntType => isinstance(x, int)
Do not mention the string module in the rlcompleter docstring.
This partially applies SF patch http://www.python.org/sf/562373
(with basestring instead of string). (It excludes the changes to
unittest.py and does not change the os.stat stuff.)
2002-06-03 12:58:32 -03:00
|
|
|
if not isinstance(x, basestring):
|
2002-04-15 10:36:47 -03:00
|
|
|
x = repr(x)
|
|
|
|
return x.zfill(width)
|
1992-03-27 11:13:31 -04:00
|
|
|
|
|
|
|
# Expand tabs in a string.
|
|
|
|
# Doesn't take non-printing chars into account, but does understand \n.
|
1995-08-10 16:42:05 -03:00
|
|
|
def expandtabs(s, tabsize=8):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""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).
|
|
|
|
|
|
|
|
"""
|
2000-07-03 04:23:13 -03:00
|
|
|
return s.expandtabs(tabsize)
|
1992-10-18 14:09:59 -03:00
|
|
|
|
1996-05-28 20:08:45 -03:00
|
|
|
# Character translation through look-up table.
|
1996-07-23 15:12:39 -03:00
|
|
|
def translate(s, table, deletions=""):
|
2000-12-18 22:39:08 -04:00
|
|
|
"""translate(s,table [,deletions]) -> string
|
1999-10-12 16:54:53 -03:00
|
|
|
|
|
|
|
Return a copy of the string s, where all characters occurring
|
2000-12-18 22:39:08 -04:00
|
|
|
in the optional argument deletions are removed, and the
|
1999-10-12 16:54:53 -03:00
|
|
|
remaining characters have been mapped through the given
|
2000-12-18 22:39:08 -04:00
|
|
|
translation table, which must be a string of length 256. The
|
|
|
|
deletions argument is not allowed for Unicode strings.
|
1999-10-12 16:54:53 -03:00
|
|
|
|
|
|
|
"""
|
2007-04-12 01:10:00 -03:00
|
|
|
if deletions or table is None:
|
2000-12-18 22:39:08 -04:00
|
|
|
return s.translate(table, deletions)
|
|
|
|
else:
|
|
|
|
# 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])
|
1992-10-18 14:09:59 -03:00
|
|
|
|
1996-06-11 15:43:00 -03:00
|
|
|
# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
|
|
|
|
def capitalize(s):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""capitalize(s) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a copy of the string s with only its first character
|
|
|
|
capitalized.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
|
|
|
return s.capitalize()
|
1996-06-11 15:43:00 -03:00
|
|
|
|
1997-03-25 12:50:31 -04:00
|
|
|
# Substring replacement (global)
|
2000-03-10 19:22:10 -04:00
|
|
|
def replace(s, old, new, maxsplit=-1):
|
1999-10-12 16:54:53 -03:00
|
|
|
"""replace (str, old, new[, maxsplit]) -> string
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
Return a copy of string str with all occurrences of substring
|
|
|
|
old replaced by new. If the optional argument maxsplit is
|
2010-08-09 05:47:15 -03:00
|
|
|
given, only the first maxsplit occurrences are replaced. A
|
|
|
|
negative value of maxsplit signifies all occurances.
|
1997-12-29 15:26:28 -04:00
|
|
|
|
1999-10-12 16:54:53 -03:00
|
|
|
"""
|
|
|
|
return s.replace(old, new, maxsplit)
|
1997-03-25 12:50:31 -04:00
|
|
|
|
|
|
|
|
1992-10-18 14:09:59 -03:00
|
|
|
# Try importing optional built-in module "strop" -- if it exists,
|
|
|
|
# it redefines some string operations that are 100-1000 times faster.
|
1993-07-29 06:37:38 -03:00
|
|
|
# It also defines values for whitespace, lowercase and uppercase
|
|
|
|
# that match <ctype.h>'s definitions.
|
1992-10-18 14:09:59 -03:00
|
|
|
|
|
|
|
try:
|
1999-10-12 16:54:53 -03:00
|
|
|
from strop import maketrans, lowercase, uppercase, whitespace
|
|
|
|
letters = lowercase + uppercase
|
1994-08-01 08:34:53 -03:00
|
|
|
except ImportError:
|
2000-02-10 12:21:11 -04:00
|
|
|
pass # Use the original versions
|
Backport of PEP 3101, Advanced String Formatting, from py3k.
Highlights:
- Adding PyObject_Format.
- Adding string.Format class.
- Adding __format__ for str, unicode, int, long, float, datetime.
- Adding builtin format.
- Adding ''.format and u''.format.
- str/unicode fixups for formatters.
The files in Objects/stringlib that implement PEP 3101 (stringdefs.h,
unicodedefs.h, formatter.h, string_format.h) are identical in trunk
and py3k. Any changes from here on should be made to trunk, and
changes will propogate to py3k).
2008-02-17 15:46:49 -04:00
|
|
|
|
|
|
|
########################################################################
|
|
|
|
# the Formatter class
|
|
|
|
# see PEP 3101 for details and purpose of this class
|
|
|
|
|
2008-11-08 21:52:32 -04:00
|
|
|
# The hard parts are reused from the C implementation. They're exposed as "_"
|
|
|
|
# prefixed methods of str and unicode.
|
Backport of PEP 3101, Advanced String Formatting, from py3k.
Highlights:
- Adding PyObject_Format.
- Adding string.Format class.
- Adding __format__ for str, unicode, int, long, float, datetime.
- Adding builtin format.
- Adding ''.format and u''.format.
- str/unicode fixups for formatters.
The files in Objects/stringlib that implement PEP 3101 (stringdefs.h,
unicodedefs.h, formatter.h, string_format.h) are identical in trunk
and py3k. Any changes from here on should be made to trunk, and
changes will propogate to py3k).
2008-02-17 15:46:49 -04:00
|
|
|
|
|
|
|
# The overall parser is implemented in str._formatter_parser.
|
|
|
|
# The field name parser is implemented in str._formatter_field_name_split
|
|
|
|
|
|
|
|
class Formatter(object):
|
|
|
|
def format(self, format_string, *args, **kwargs):
|
|
|
|
return self.vformat(format_string, args, kwargs)
|
|
|
|
|
|
|
|
def vformat(self, format_string, args, kwargs):
|
|
|
|
used_args = set()
|
|
|
|
result = self._vformat(format_string, args, kwargs, used_args, 2)
|
|
|
|
self.check_unused_args(used_args, args, kwargs)
|
|
|
|
return result
|
|
|
|
|
|
|
|
def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
|
|
|
|
if recursion_depth < 0:
|
|
|
|
raise ValueError('Max string recursion exceeded')
|
|
|
|
result = []
|
|
|
|
for literal_text, field_name, format_spec, conversion in \
|
|
|
|
self.parse(format_string):
|
|
|
|
|
|
|
|
# output the literal text
|
|
|
|
if literal_text:
|
|
|
|
result.append(literal_text)
|
|
|
|
|
|
|
|
# if there's a field, output it
|
|
|
|
if field_name is not None:
|
|
|
|
# this is some markup, find the object and do
|
|
|
|
# the formatting
|
|
|
|
|
|
|
|
# given the field_name, find the object it references
|
|
|
|
# and the argument it came from
|
|
|
|
obj, arg_used = self.get_field(field_name, args, kwargs)
|
|
|
|
used_args.add(arg_used)
|
|
|
|
|
|
|
|
# do any conversion on the resulting object
|
|
|
|
obj = self.convert_field(obj, conversion)
|
|
|
|
|
|
|
|
# expand the format spec, if needed
|
|
|
|
format_spec = self._vformat(format_spec, args, kwargs,
|
|
|
|
used_args, recursion_depth-1)
|
|
|
|
|
|
|
|
# format the object and append to the result
|
|
|
|
result.append(self.format_field(obj, format_spec))
|
|
|
|
|
|
|
|
return ''.join(result)
|
|
|
|
|
|
|
|
|
|
|
|
def get_value(self, key, args, kwargs):
|
|
|
|
if isinstance(key, (int, long)):
|
|
|
|
return args[key]
|
|
|
|
else:
|
|
|
|
return kwargs[key]
|
|
|
|
|
|
|
|
|
|
|
|
def check_unused_args(self, used_args, args, kwargs):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def format_field(self, value, format_spec):
|
|
|
|
return format(value, format_spec)
|
|
|
|
|
|
|
|
|
|
|
|
def convert_field(self, value, conversion):
|
|
|
|
# do any conversion on the resulting object
|
|
|
|
if conversion == 'r':
|
|
|
|
return repr(value)
|
|
|
|
elif conversion == 's':
|
|
|
|
return str(value)
|
|
|
|
elif conversion is None:
|
|
|
|
return value
|
|
|
|
raise ValueError("Unknown converion specifier {0!s}".format(conversion))
|
|
|
|
|
|
|
|
|
|
|
|
# returns an iterable that contains tuples of the form:
|
|
|
|
# (literal_text, field_name, format_spec, conversion)
|
|
|
|
# literal_text can be zero length
|
|
|
|
# field_name can be None, in which case there's no
|
|
|
|
# object to format and output
|
|
|
|
# if field_name is not None, it is looked up, formatted
|
|
|
|
# with format_spec and conversion and then used
|
|
|
|
def parse(self, format_string):
|
|
|
|
return format_string._formatter_parser()
|
|
|
|
|
|
|
|
|
|
|
|
# given a field_name, find the object it references.
|
|
|
|
# field_name: the field being looked up, e.g. "0.name"
|
|
|
|
# or "lookup[3]"
|
|
|
|
# used_args: a set of which args have been used
|
|
|
|
# args, kwargs: as passed in to vformat
|
|
|
|
def get_field(self, field_name, args, kwargs):
|
|
|
|
first, rest = field_name._formatter_field_name_split()
|
|
|
|
|
|
|
|
obj = self.get_value(first, args, kwargs)
|
|
|
|
|
|
|
|
# loop through the rest of the field_name, doing
|
|
|
|
# getattr or getitem as needed
|
|
|
|
for is_attr, i in rest:
|
|
|
|
if is_attr:
|
|
|
|
obj = getattr(obj, i)
|
|
|
|
else:
|
|
|
|
obj = obj[i]
|
|
|
|
|
|
|
|
return obj, first
|