blob: d762e040b1123ca7e21c1e248403d02aaf1dd58d [file] [log] [blame]
Skip Montanaro0b874442003-10-03 14:05:26 +00001"""A collection of string operations (most are no longer used).
Guido van Rossumc6360141990-10-13 19:23:40 +00002
Skip Montanaro0b874442003-10-03 14:05:26 +00003Warning: most of the code you see here isn't normally used nowadays.
4Beginning with Python 1.6, many of these functions are implemented as
5methods on the standard string object. They used to be implemented by
6a built-in module called strop, but strop is now obsolete itself.
Guido van Rossum20032041997-12-29 19:26:28 +00007
8Public module variables:
9
10whitespace -- a string containing all characters considered whitespace
11lowercase -- a string containing all characters considered lowercase letters
12uppercase -- a string containing all characters considered uppercase letters
13letters -- a string containing all characters considered letters
14digits -- a string containing all characters considered decimal digits
15hexdigits -- a string containing all characters considered hexadecimal digits
16octdigits -- a string containing all characters considered octal digits
Fred Drakefd64c592000-09-18 19:38:11 +000017punctuation -- a string containing all characters considered punctuation
18printable -- a string containing all characters considered printable
Guido van Rossum20032041997-12-29 19:26:28 +000019
20"""
21
Guido van Rossumc6360141990-10-13 19:23:40 +000022# Some strings for ctype-style character classification
Guido van Rossum8e2ec561993-07-29 09:37:38 +000023whitespace = ' \t\n\r\v\f'
Guido van Rossumc6360141990-10-13 19:23:40 +000024lowercase = 'abcdefghijklmnopqrstuvwxyz'
25uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
26letters = lowercase + uppercase
Fred Drake960fdf92001-07-20 18:38:26 +000027ascii_lowercase = lowercase
28ascii_uppercase = uppercase
29ascii_letters = ascii_lowercase + ascii_uppercase
Guido van Rossumc6360141990-10-13 19:23:40 +000030digits = '0123456789'
31hexdigits = digits + 'abcdef' + 'ABCDEF'
32octdigits = '01234567'
Tim Peters495ad3c2001-01-15 01:36:40 +000033punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
Fred Drake6b2320f2000-09-18 16:46:17 +000034printable = digits + letters + punctuation + whitespace
Guido van Rossumc6360141990-10-13 19:23:40 +000035
36# Case conversion helpers
Martin v. Löwis5357c652002-10-14 20:03:40 +000037# Use str to convert Unicode literal in case of -U
38l = map(chr, xrange(256))
39_idmap = str('').join(l)
40del l
Guido van Rossumc6360141990-10-13 19:23:40 +000041
Barry Warsaw8bee7612004-08-25 02:22:30 +000042# Functions which aren't available as string methods.
43
44# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
Barry Warsaw8bee7612004-08-25 02:22:30 +000045def capwords(s, sep=None):
Ezio Melotti9aac2452009-09-26 11:20:53 +000046 """capwords(s [,sep]) -> string
Barry Warsaw8bee7612004-08-25 02:22:30 +000047
48 Split the argument into words using split, capitalize each
49 word using capitalize, and join the capitalized words using
Ezio Melotti9aac2452009-09-26 11:20:53 +000050 join. If the optional second argument sep is absent or None,
51 runs of whitespace characters are replaced by a single space
52 and leading and trailing whitespace are removed, otherwise
53 sep is used to split and join the words.
Barry Warsaw8bee7612004-08-25 02:22:30 +000054
55 """
Ezio Melotti9aac2452009-09-26 11:20:53 +000056 return (sep or ' ').join(x.capitalize() for x in s.split(sep))
Barry Warsaw8bee7612004-08-25 02:22:30 +000057
58
59# Construct a translation string
60_idmapL = None
61def maketrans(fromstr, tostr):
62 """maketrans(frm, to) -> string
63
64 Return a translation table (a string of 256 bytes long)
65 suitable for use in string.translate. The strings frm and to
66 must be of the same length.
67
68 """
69 if len(fromstr) != len(tostr):
70 raise ValueError, "maketrans arguments must have same length"
71 global _idmapL
72 if not _idmapL:
Georg Brandl74bbc792008-07-18 19:06:13 +000073 _idmapL = list(_idmap)
Barry Warsaw8bee7612004-08-25 02:22:30 +000074 L = _idmapL[:]
75 fromstr = map(ord, fromstr)
76 for i in range(len(fromstr)):
77 L[fromstr[i]] = tostr[i]
78 return ''.join(L)
79
80
Raymond Hettinger57aef9c2004-12-07 07:55:07 +000081
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +000082####################################################################
Barry Warsaw8bee7612004-08-25 02:22:30 +000083import re as _re
84
Barry Warsaw46b629c2004-09-13 14:35:04 +000085class _multimap:
86 """Helper class for combining multiple mappings.
87
88 Used by .{safe_,}substitute() to combine the mapping and keyword
89 arguments.
90 """
91 def __init__(self, primary, secondary):
92 self._primary = primary
93 self._secondary = secondary
94
95 def __getitem__(self, key):
96 try:
97 return self._primary[key]
98 except KeyError:
99 return self._secondary[key]
100
101
Barry Warsaw12827c12004-09-10 03:08:08 +0000102class _TemplateMetaclass(type):
103 pattern = r"""
Raymond Hettinger55593c32004-09-26 18:56:44 +0000104 %(delim)s(?:
105 (?P<escaped>%(delim)s) | # Escape sequence of two delimiters
106 (?P<named>%(id)s) | # delimiter and a Python identifier
107 {(?P<braced>%(id)s)} | # delimiter and a braced identifier
108 (?P<invalid>) # Other ill-formed delimiter exprs
109 )
Barry Warsaw12827c12004-09-10 03:08:08 +0000110 """
111
112 def __init__(cls, name, bases, dct):
Guido van Rossumf102e242007-03-23 18:53:03 +0000113 super(_TemplateMetaclass, cls).__init__(name, bases, dct)
Barry Warsaw12827c12004-09-10 03:08:08 +0000114 if 'pattern' in dct:
115 pattern = cls.pattern
116 else:
117 pattern = _TemplateMetaclass.pattern % {
Barry Warsaw17cb6002004-09-18 00:06:34 +0000118 'delim' : _re.escape(cls.delimiter),
Barry Warsaw12827c12004-09-10 03:08:08 +0000119 'id' : cls.idpattern,
120 }
121 cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
122
123
124class Template:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000125 """A string class for supporting $-substitutions."""
Barry Warsaw12827c12004-09-10 03:08:08 +0000126 __metaclass__ = _TemplateMetaclass
127
Barry Warsaw17cb6002004-09-18 00:06:34 +0000128 delimiter = '$'
Barry Warsaw12827c12004-09-10 03:08:08 +0000129 idpattern = r'[_a-z][_a-z0-9]*'
130
131 def __init__(self, template):
132 self.template = template
Barry Warsaw8bee7612004-08-25 02:22:30 +0000133
134 # Search for $$, $identifier, ${identifier}, and any bare $'s
Barry Warsaw8bee7612004-08-25 02:22:30 +0000135
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000136 def _invalid(self, mo):
137 i = mo.start('invalid')
Barry Warsaw12827c12004-09-10 03:08:08 +0000138 lines = self.template[:i].splitlines(True)
139 if not lines:
140 colno = 1
141 lineno = 1
142 else:
143 colno = i - len(''.join(lines[:-1]))
144 lineno = len(lines)
145 raise ValueError('Invalid placeholder in string: line %d, col %d' %
146 (lineno, colno))
147
Barry Warsawb6234a92004-09-13 15:25:15 +0000148 def substitute(self, *args, **kws):
149 if len(args) > 1:
150 raise TypeError('Too many positional arguments')
151 if not args:
152 mapping = kws
Barry Warsaw46b629c2004-09-13 14:35:04 +0000153 elif kws:
Barry Warsawb6234a92004-09-13 15:25:15 +0000154 mapping = _multimap(kws, args[0])
155 else:
156 mapping = args[0]
Barry Warsaw46b629c2004-09-13 14:35:04 +0000157 # Helper function for .sub()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000158 def convert(mo):
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000159 # Check the most common path first.
160 named = mo.group('named') or mo.group('braced')
161 if named is not None:
162 val = mapping[named]
163 # We use this idiom instead of str() because the latter will
164 # fail if val is a Unicode containing non-ASCII characters.
Thomas Woutersadd19112006-07-05 11:03:49 +0000165 return '%s' % (val,)
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000166 if mo.group('escaped') is not None:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000167 return self.delimiter
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000168 if mo.group('invalid') is not None:
169 self._invalid(mo)
Neal Norwitz6627a962004-10-17 16:27:18 +0000170 raise ValueError('Unrecognized named group in pattern',
171 self.pattern)
Barry Warsaw12827c12004-09-10 03:08:08 +0000172 return self.pattern.sub(convert, self.template)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000173
Barry Warsawb6234a92004-09-13 15:25:15 +0000174 def safe_substitute(self, *args, **kws):
175 if len(args) > 1:
176 raise TypeError('Too many positional arguments')
177 if not args:
178 mapping = kws
Barry Warsaw46b629c2004-09-13 14:35:04 +0000179 elif kws:
Barry Warsawb6234a92004-09-13 15:25:15 +0000180 mapping = _multimap(kws, args[0])
181 else:
182 mapping = args[0]
Barry Warsaw46b629c2004-09-13 14:35:04 +0000183 # Helper function for .sub()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000184 def convert(mo):
Florent Xiclunaff05e522010-09-18 23:34:07 +0000185 named = mo.group('named') or mo.group('braced')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000186 if named is not None:
187 try:
Barry Warsaw12827c12004-09-10 03:08:08 +0000188 # We use this idiom instead of str() because the latter
189 # will fail if val is a Unicode containing non-ASCII
Thomas Woutersadd19112006-07-05 11:03:49 +0000190 return '%s' % (mapping[named],)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000191 except KeyError:
Florent Xiclunaff05e522010-09-18 23:34:07 +0000192 return mo.group()
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000193 if mo.group('escaped') is not None:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000194 return self.delimiter
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000195 if mo.group('invalid') is not None:
Florent Xiclunaff05e522010-09-18 23:34:07 +0000196 return mo.group()
Neal Norwitz6627a962004-10-17 16:27:18 +0000197 raise ValueError('Unrecognized named group in pattern',
198 self.pattern)
Barry Warsaw12827c12004-09-10 03:08:08 +0000199 return self.pattern.sub(convert, self.template)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000200
201
Raymond Hettinger57aef9c2004-12-07 07:55:07 +0000202
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000203####################################################################
Barry Warsaw8bee7612004-08-25 02:22:30 +0000204# NOTE: Everything below here is deprecated. Use string methods instead.
205# This stuff will go away in Python 3.0.
206
Guido van Rossum710c3521994-08-17 13:16:11 +0000207# Backward compatible names for exceptions
208index_error = ValueError
209atoi_error = ValueError
210atof_error = ValueError
211atol_error = ValueError
212
Guido van Rossumc6360141990-10-13 19:23:40 +0000213# convert UPPER CASE letters to lower case
214def lower(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000215 """lower(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000216
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217 Return a copy of the string s converted to lowercase.
Guido van Rossum20032041997-12-29 19:26:28 +0000218
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000219 """
220 return s.lower()
Guido van Rossumc6360141990-10-13 19:23:40 +0000221
222# Convert lower case letters to UPPER CASE
223def upper(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000224 """upper(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000225
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000226 Return a copy of the string s converted to uppercase.
Guido van Rossum20032041997-12-29 19:26:28 +0000227
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000228 """
229 return s.upper()
Guido van Rossumc6360141990-10-13 19:23:40 +0000230
231# Swap lower case letters and UPPER CASE
232def swapcase(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000233 """swapcase(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000234
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000235 Return a copy of the string s with upper case characters
236 converted to lowercase and vice versa.
Guido van Rossum20032041997-12-29 19:26:28 +0000237
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000238 """
239 return s.swapcase()
Guido van Rossumc6360141990-10-13 19:23:40 +0000240
241# Strip leading and trailing tabs and spaces
Martin v. Löwis1f046102002-11-08 12:09:59 +0000242def strip(s, chars=None):
Neal Norwitza4864a22002-11-14 03:31:32 +0000243 """strip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000244
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000245 Return a copy of the string s with leading and trailing
246 whitespace removed.
Neal Norwitzffe33b72003-04-10 22:35:32 +0000247 If chars is given and not None, remove characters in chars instead.
Neal Norwitza4864a22002-11-14 03:31:32 +0000248 If chars is unicode, S will be converted to unicode before stripping.
Guido van Rossum20032041997-12-29 19:26:28 +0000249
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000250 """
Martin v. Löwis1f046102002-11-08 12:09:59 +0000251 return s.strip(chars)
Guido van Rossumc6360141990-10-13 19:23:40 +0000252
Guido van Rossum306a8a61996-08-08 18:40:59 +0000253# Strip leading tabs and spaces
Neal Norwitzffe33b72003-04-10 22:35:32 +0000254def lstrip(s, chars=None):
255 """lstrip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000256
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000257 Return a copy of the string s with leading whitespace removed.
Neal Norwitzffe33b72003-04-10 22:35:32 +0000258 If chars is given and not None, remove characters in chars instead.
Guido van Rossum20032041997-12-29 19:26:28 +0000259
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000260 """
Neal Norwitzffe33b72003-04-10 22:35:32 +0000261 return s.lstrip(chars)
Guido van Rossum306a8a61996-08-08 18:40:59 +0000262
263# Strip trailing tabs and spaces
Neal Norwitzffe33b72003-04-10 22:35:32 +0000264def rstrip(s, chars=None):
265 """rstrip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000266
Neal Norwitzffe33b72003-04-10 22:35:32 +0000267 Return a copy of the string s with trailing whitespace removed.
268 If chars is given and not None, remove characters in chars instead.
Guido van Rossum20032041997-12-29 19:26:28 +0000269
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000270 """
Neal Norwitzffe33b72003-04-10 22:35:32 +0000271 return s.rstrip(chars)
Guido van Rossum306a8a61996-08-08 18:40:59 +0000272
273
Guido van Rossumc6360141990-10-13 19:23:40 +0000274# Split a string into a list of space/tab-separated words
Guido van Rossum8f0c5a72000-03-10 23:22:10 +0000275def split(s, sep=None, maxsplit=-1):
Fred Drakee4f13661999-11-04 19:19:48 +0000276 """split(s [,sep [,maxsplit]]) -> list of strings
Guido van Rossum20032041997-12-29 19:26:28 +0000277
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000278 Return a list of the words in the string s, using sep as the
Fred Drake14537542002-01-30 16:15:13 +0000279 delimiter string. If maxsplit is given, splits at no more than
280 maxsplit places (resulting in at most maxsplit+1 words). If sep
Walter Dörwald065a32f2004-09-14 09:45:10 +0000281 is not specified or is None, any whitespace string is a separator.
Guido van Rossum20032041997-12-29 19:26:28 +0000282
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000283 (split and splitfields are synonymous)
Guido van Rossum20032041997-12-29 19:26:28 +0000284
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000285 """
286 return s.split(sep, maxsplit)
287splitfields = split
Guido van Rossumfac38b71991-04-07 13:42:19 +0000288
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000289# Split a string into a list of space/tab-separated words
290def rsplit(s, sep=None, maxsplit=-1):
291 """rsplit(s [,sep [,maxsplit]]) -> list of strings
292
293 Return a list of the words in the string s, using sep as the
294 delimiter string, starting at the end of the string and working
295 to the front. If maxsplit is given, at most maxsplit splits are
296 done. If sep is not specified or is None, any whitespace string
297 is a separator.
298 """
299 return s.rsplit(sep, maxsplit)
300
Guido van Rossum2ab19921995-06-22 18:58:00 +0000301# Join fields with optional separator
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000302def join(words, sep = ' '):
303 """join(list [,sep]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000304
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000305 Return a string composed of the words in list, with
Thomas Wouters7e474022000-07-16 12:04:32 +0000306 intervening occurrences of sep. The default separator is a
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000307 single space.
Guido van Rossum20032041997-12-29 19:26:28 +0000308
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000309 (joinfields and join are synonymous)
Guido van Rossum20032041997-12-29 19:26:28 +0000310
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000311 """
312 return sep.join(words)
313joinfields = join
314
Guido van Rossumd3166071993-05-24 14:16:22 +0000315# Find substring, raise exception if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000316def index(s, *args):
317 """index(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000318
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000319 Like find but raises ValueError when the substring is not found.
Guido van Rossum20032041997-12-29 19:26:28 +0000320
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000321 """
Fred Drake046d2722000-07-03 07:23:13 +0000322 return s.index(*args)
Guido van Rossumd3166071993-05-24 14:16:22 +0000323
Guido van Rossume65cce51993-11-08 15:05:21 +0000324# Find last substring, raise exception if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000325def rindex(s, *args):
326 """rindex(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000327
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000328 Like rfind but raises ValueError when the substring is not found.
Guido van Rossum20032041997-12-29 19:26:28 +0000329
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000330 """
Fred Drake046d2722000-07-03 07:23:13 +0000331 return s.rindex(*args)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000332
333# Count non-overlapping occurrences of substring
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000334def count(s, *args):
335 """count(s, sub[, start[,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000336
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000337 Return the number of occurrences of substring sub in string
338 s[start:end]. Optional arguments start and end are
339 interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000340
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000341 """
Fred Drake046d2722000-07-03 07:23:13 +0000342 return s.count(*args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000343
Guido van Rossumd3166071993-05-24 14:16:22 +0000344# Find substring, return -1 if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000345def find(s, *args):
346 """find(s, sub [,start [,end]]) -> in
Guido van Rossum20032041997-12-29 19:26:28 +0000347
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000348 Return the lowest index in s where substring sub is found,
349 such that sub is contained within s[start,end]. Optional
350 arguments start and end are interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000351
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000352 Return -1 on failure.
Guido van Rossum20032041997-12-29 19:26:28 +0000353
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000354 """
Fred Drake046d2722000-07-03 07:23:13 +0000355 return s.find(*args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000356
Guido van Rossume65cce51993-11-08 15:05:21 +0000357# Find last substring, return -1 if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000358def rfind(s, *args):
359 """rfind(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000360
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000361 Return the highest index in s where substring sub is found,
362 such that sub is contained within s[start,end]. Optional
363 arguments start and end are interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000364
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000365 Return -1 on failure.
Guido van Rossum20032041997-12-29 19:26:28 +0000366
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000367 """
Fred Drake046d2722000-07-03 07:23:13 +0000368 return s.rfind(*args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000369
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000370# for a bit of speed
371_float = float
372_int = int
373_long = long
Guido van Rossumd0753e21997-12-10 22:59:55 +0000374
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000375# Convert string to float
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000376def atof(s):
377 """atof(s) -> float
Guido van Rossum20032041997-12-29 19:26:28 +0000378
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000379 Return the floating point number represented by the string s.
Guido van Rossum20032041997-12-29 19:26:28 +0000380
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000381 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000382 return _float(s)
383
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000384
Guido van Rossumc6360141990-10-13 19:23:40 +0000385# Convert string to integer
Guido van Rossum9e896b32000-04-05 20:11:21 +0000386def atoi(s , base=10):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000387 """atoi(s [,base]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000388
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000389 Return the integer represented by the string s in the given
390 base, which defaults to 10. The string s must consist of one
391 or more digits, possibly preceded by a sign. If base is 0, it
392 is chosen from the leading characters of s, 0 for octal, 0x or
393 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
394 accepted.
Guido van Rossum20032041997-12-29 19:26:28 +0000395
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000396 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000397 return _int(s, base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000398
Guido van Rossumc6360141990-10-13 19:23:40 +0000399
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000400# Convert string to long integer
Guido van Rossum9e896b32000-04-05 20:11:21 +0000401def atol(s, base=10):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000402 """atol(s [,base]) -> long
Guido van Rossum20032041997-12-29 19:26:28 +0000403
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000404 Return the long integer represented by the string s in the
405 given base, which defaults to 10. The string s must consist
406 of one or more digits, possibly preceded by a sign. If base
407 is 0, it is chosen from the leading characters of s, 0 for
408 octal, 0x or 0X for hexadecimal. If base is 16, a preceding
409 0x or 0X is accepted. A trailing L or l is not accepted,
410 unless base is 0.
Guido van Rossum20032041997-12-29 19:26:28 +0000411
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000412 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000413 return _long(s, base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000414
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000415
Guido van Rossumc6360141990-10-13 19:23:40 +0000416# Left-justify a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000417def ljust(s, width, *args):
418 """ljust(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000419
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000420 Return a left-justified version of s, in a field of the
421 specified width, padded with spaces as needed. The string is
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000422 never truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000423
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000424 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000425 return s.ljust(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000426
427# Right-justify a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000428def rjust(s, width, *args):
429 """rjust(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000430
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000431 Return a right-justified version of s, in a field of the
432 specified width, padded with spaces as needed. The string is
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000433 never truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000434
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000435 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000436 return s.rjust(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000437
438# Center a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000439def center(s, width, *args):
440 """center(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000441
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000442 Return a center version of s, in a field of the specified
443 width. padded with spaces as needed. The string is never
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000444 truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000445
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000446 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000447 return s.center(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000448
449# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
450# Decadent feature: the argument may be a string or a number
451# (Use of this is deprecated; it should be a string as with ljust c.s.)
452def zfill(x, width):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000453 """zfill(x, width) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000454
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000455 Pad a numeric string x with zeros on the left, to fill a field
456 of the specified width. The string x is never truncated.
Guido van Rossum20032041997-12-29 19:26:28 +0000457
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000458 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000459 if not isinstance(x, basestring):
Walter Dörwald068325e2002-04-15 13:36:47 +0000460 x = repr(x)
461 return x.zfill(width)
Guido van Rossum6ff2e901992-03-27 15:13:31 +0000462
463# Expand tabs in a string.
464# Doesn't take non-printing chars into account, but does understand \n.
Guido van Rossum894a7bb1995-08-10 19:42:05 +0000465def expandtabs(s, tabsize=8):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000466 """expandtabs(s [,tabsize]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000467
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000468 Return a copy of the string s with all tab characters replaced
469 by the appropriate number of spaces, depending on the current
470 column, and the tabsize (default 8).
Guido van Rossum20032041997-12-29 19:26:28 +0000471
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000472 """
Fred Drake046d2722000-07-03 07:23:13 +0000473 return s.expandtabs(tabsize)
Guido van Rossum2db91351992-10-18 17:09:59 +0000474
Guido van Rossum25395281996-05-28 23:08:45 +0000475# Character translation through look-up table.
Guido van Rossumed7253c1996-07-23 18:12:39 +0000476def translate(s, table, deletions=""):
Guido van Rossum5aff7752000-12-19 02:39:08 +0000477 """translate(s,table [,deletions]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000478
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000479 Return a copy of the string s, where all characters occurring
Guido van Rossum5aff7752000-12-19 02:39:08 +0000480 in the optional argument deletions are removed, and the
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000481 remaining characters have been mapped through the given
Guido van Rossum5aff7752000-12-19 02:39:08 +0000482 translation table, which must be a string of length 256. The
483 deletions argument is not allowed for Unicode strings.
Guido van Rossum20032041997-12-29 19:26:28 +0000484
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000485 """
Raymond Hettinger4db5fe92007-04-12 04:10:00 +0000486 if deletions or table is None:
Guido van Rossum5aff7752000-12-19 02:39:08 +0000487 return s.translate(table, deletions)
488 else:
489 # Add s[:0] so that if s is Unicode and table is an 8-bit string,
490 # table is converted to Unicode. This means that table *cannot*
491 # be a dictionary -- for that feature, use u.translate() directly.
492 return s.translate(table + s[:0])
Guido van Rossum2db91351992-10-18 17:09:59 +0000493
Guido van Rossum8775d8b1996-06-11 18:43:00 +0000494# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
495def capitalize(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000496 """capitalize(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000497
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000498 Return a copy of the string s with only its first character
499 capitalized.
Guido van Rossum20032041997-12-29 19:26:28 +0000500
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000501 """
502 return s.capitalize()
Guido van Rossum8775d8b1996-06-11 18:43:00 +0000503
Guido van Rossum1eb9a811997-03-25 16:50:31 +0000504# Substring replacement (global)
Senthil Kumarana240cb12010-09-08 12:40:45 +0000505def replace(s, old, new, maxreplace=-1):
506 """replace (str, old, new[, maxreplace]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000507
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000508 Return a copy of string str with all occurrences of substring
Senthil Kumarana240cb12010-09-08 12:40:45 +0000509 old replaced by new. If the optional argument maxreplace is
510 given, only the first maxreplace occurrences are replaced.
Guido van Rossum20032041997-12-29 19:26:28 +0000511
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000512 """
Senthil Kumarana240cb12010-09-08 12:40:45 +0000513 return s.replace(old, new, maxreplace)
Guido van Rossum1eb9a811997-03-25 16:50:31 +0000514
515
Guido van Rossum2db91351992-10-18 17:09:59 +0000516# Try importing optional built-in module "strop" -- if it exists,
517# it redefines some string operations that are 100-1000 times faster.
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000518# It also defines values for whitespace, lowercase and uppercase
519# that match <ctype.h>'s definitions.
Guido van Rossum2db91351992-10-18 17:09:59 +0000520
521try:
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000522 from strop import maketrans, lowercase, uppercase, whitespace
523 letters = lowercase + uppercase
Guido van Rossumb6775db1994-08-01 11:34:53 +0000524except ImportError:
Fred Drake857c4c32000-02-10 16:21:11 +0000525 pass # Use the original versions
Eric Smitha9f7d622008-02-17 19:46:49 +0000526
527########################################################################
528# the Formatter class
529# see PEP 3101 for details and purpose of this class
530
Benjamin Petersonb7c95ce2008-11-09 01:52:32 +0000531# The hard parts are reused from the C implementation. They're exposed as "_"
532# prefixed methods of str and unicode.
Eric Smitha9f7d622008-02-17 19:46:49 +0000533
534# The overall parser is implemented in str._formatter_parser.
535# The field name parser is implemented in str._formatter_field_name_split
536
537class Formatter(object):
538 def format(self, format_string, *args, **kwargs):
539 return self.vformat(format_string, args, kwargs)
540
541 def vformat(self, format_string, args, kwargs):
542 used_args = set()
543 result = self._vformat(format_string, args, kwargs, used_args, 2)
544 self.check_unused_args(used_args, args, kwargs)
545 return result
546
547 def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
548 if recursion_depth < 0:
549 raise ValueError('Max string recursion exceeded')
550 result = []
551 for literal_text, field_name, format_spec, conversion in \
552 self.parse(format_string):
553
554 # output the literal text
555 if literal_text:
556 result.append(literal_text)
557
558 # if there's a field, output it
559 if field_name is not None:
560 # this is some markup, find the object and do
561 # the formatting
562
563 # given the field_name, find the object it references
564 # and the argument it came from
565 obj, arg_used = self.get_field(field_name, args, kwargs)
566 used_args.add(arg_used)
567
568 # do any conversion on the resulting object
569 obj = self.convert_field(obj, conversion)
570
571 # expand the format spec, if needed
572 format_spec = self._vformat(format_spec, args, kwargs,
573 used_args, recursion_depth-1)
574
575 # format the object and append to the result
576 result.append(self.format_field(obj, format_spec))
577
578 return ''.join(result)
579
580
581 def get_value(self, key, args, kwargs):
582 if isinstance(key, (int, long)):
583 return args[key]
584 else:
585 return kwargs[key]
586
587
588 def check_unused_args(self, used_args, args, kwargs):
589 pass
590
591
592 def format_field(self, value, format_spec):
593 return format(value, format_spec)
594
595
596 def convert_field(self, value, conversion):
597 # do any conversion on the resulting object
R David Murrayd928b6a2012-08-19 17:57:29 -0400598 if conversion is None:
599 return value
Eric Smitha9f7d622008-02-17 19:46:49 +0000600 elif conversion == 's':
601 return str(value)
R David Murrayd928b6a2012-08-19 17:57:29 -0400602 elif conversion == 'r':
603 return repr(value)
Florent Xicluna9b90cd12010-09-13 07:46:37 +0000604 raise ValueError("Unknown conversion specifier {0!s}".format(conversion))
Eric Smitha9f7d622008-02-17 19:46:49 +0000605
606
607 # returns an iterable that contains tuples of the form:
608 # (literal_text, field_name, format_spec, conversion)
609 # literal_text can be zero length
610 # field_name can be None, in which case there's no
611 # object to format and output
612 # if field_name is not None, it is looked up, formatted
613 # with format_spec and conversion and then used
614 def parse(self, format_string):
615 return format_string._formatter_parser()
616
617
618 # given a field_name, find the object it references.
619 # field_name: the field being looked up, e.g. "0.name"
620 # or "lookup[3]"
621 # used_args: a set of which args have been used
622 # args, kwargs: as passed in to vformat
623 def get_field(self, field_name, args, kwargs):
624 first, rest = field_name._formatter_field_name_split()
625
626 obj = self.get_value(first, args, kwargs)
627
628 # loop through the rest of the field_name, doing
629 # getattr or getitem as needed
630 for is_attr, i in rest:
631 if is_attr:
632 obj = getattr(obj, i)
633 else:
634 obj = obj[i]
635
636 return obj, first