blob: 6aafb65c35314a9ad167017f03a21756f38bef87 [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):
46 """capwords(s, [sep]) -> string
47
48 Split the argument into words using split, capitalize each
49 word using capitalize, and join the capitalized words using
50 join. Note that this replaces runs of whitespace characters by
51 a single space.
52
53 """
54 return (sep or ' ').join([x.capitalize() for x in s.split(sep)])
55
56
57# Construct a translation string
58_idmapL = None
59def maketrans(fromstr, tostr):
60 """maketrans(frm, to) -> string
61
62 Return a translation table (a string of 256 bytes long)
63 suitable for use in string.translate. The strings frm and to
64 must be of the same length.
65
66 """
67 if len(fromstr) != len(tostr):
68 raise ValueError, "maketrans arguments must have same length"
69 global _idmapL
70 if not _idmapL:
71 _idmapL = map(None, _idmap)
72 L = _idmapL[:]
73 fromstr = map(ord, fromstr)
74 for i in range(len(fromstr)):
75 L[fromstr[i]] = tostr[i]
76 return ''.join(L)
77
78
Raymond Hettinger57aef9c2004-12-07 07:55:07 +000079
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +000080####################################################################
Barry Warsaw8bee7612004-08-25 02:22:30 +000081import re as _re
82
Barry Warsaw46b629c2004-09-13 14:35:04 +000083class _multimap:
84 """Helper class for combining multiple mappings.
85
86 Used by .{safe_,}substitute() to combine the mapping and keyword
87 arguments.
88 """
89 def __init__(self, primary, secondary):
90 self._primary = primary
91 self._secondary = secondary
92
93 def __getitem__(self, key):
94 try:
95 return self._primary[key]
96 except KeyError:
97 return self._secondary[key]
98
99
Barry Warsaw12827c12004-09-10 03:08:08 +0000100class _TemplateMetaclass(type):
101 pattern = r"""
Raymond Hettinger55593c32004-09-26 18:56:44 +0000102 %(delim)s(?:
103 (?P<escaped>%(delim)s) | # Escape sequence of two delimiters
104 (?P<named>%(id)s) | # delimiter and a Python identifier
105 {(?P<braced>%(id)s)} | # delimiter and a braced identifier
106 (?P<invalid>) # Other ill-formed delimiter exprs
107 )
Barry Warsaw12827c12004-09-10 03:08:08 +0000108 """
109
110 def __init__(cls, name, bases, dct):
111 super(_TemplateMetaclass, cls).__init__(name, bases, dct)
112 if 'pattern' in dct:
113 pattern = cls.pattern
114 else:
115 pattern = _TemplateMetaclass.pattern % {
Barry Warsaw17cb6002004-09-18 00:06:34 +0000116 'delim' : _re.escape(cls.delimiter),
Barry Warsaw12827c12004-09-10 03:08:08 +0000117 'id' : cls.idpattern,
118 }
119 cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
120
121
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000122class Template(metaclass=_TemplateMetaclass):
Barry Warsaw8bee7612004-08-25 02:22:30 +0000123 """A string class for supporting $-substitutions."""
Barry Warsaw12827c12004-09-10 03:08:08 +0000124
Barry Warsaw17cb6002004-09-18 00:06:34 +0000125 delimiter = '$'
Barry Warsaw12827c12004-09-10 03:08:08 +0000126 idpattern = r'[_a-z][_a-z0-9]*'
127
128 def __init__(self, template):
129 self.template = template
Barry Warsaw8bee7612004-08-25 02:22:30 +0000130
131 # Search for $$, $identifier, ${identifier}, and any bare $'s
Barry Warsaw8bee7612004-08-25 02:22:30 +0000132
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000133 def _invalid(self, mo):
134 i = mo.start('invalid')
Barry Warsaw12827c12004-09-10 03:08:08 +0000135 lines = self.template[:i].splitlines(True)
136 if not lines:
137 colno = 1
138 lineno = 1
139 else:
140 colno = i - len(''.join(lines[:-1]))
141 lineno = len(lines)
142 raise ValueError('Invalid placeholder in string: line %d, col %d' %
143 (lineno, colno))
144
Barry Warsawb6234a92004-09-13 15:25:15 +0000145 def substitute(self, *args, **kws):
146 if len(args) > 1:
147 raise TypeError('Too many positional arguments')
148 if not args:
149 mapping = kws
Barry Warsaw46b629c2004-09-13 14:35:04 +0000150 elif kws:
Barry Warsawb6234a92004-09-13 15:25:15 +0000151 mapping = _multimap(kws, args[0])
152 else:
153 mapping = args[0]
Barry Warsaw46b629c2004-09-13 14:35:04 +0000154 # Helper function for .sub()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000155 def convert(mo):
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000156 # Check the most common path first.
157 named = mo.group('named') or mo.group('braced')
158 if named is not None:
159 val = mapping[named]
160 # We use this idiom instead of str() because the latter will
161 # fail if val is a Unicode containing non-ASCII characters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162 return '%s' % (val,)
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000163 if mo.group('escaped') is not None:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000164 return self.delimiter
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000165 if mo.group('invalid') is not None:
166 self._invalid(mo)
Neal Norwitz6627a962004-10-17 16:27:18 +0000167 raise ValueError('Unrecognized named group in pattern',
168 self.pattern)
Barry Warsaw12827c12004-09-10 03:08:08 +0000169 return self.pattern.sub(convert, self.template)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000170
Barry Warsawb6234a92004-09-13 15:25:15 +0000171 def safe_substitute(self, *args, **kws):
172 if len(args) > 1:
173 raise TypeError('Too many positional arguments')
174 if not args:
175 mapping = kws
Barry Warsaw46b629c2004-09-13 14:35:04 +0000176 elif kws:
Barry Warsawb6234a92004-09-13 15:25:15 +0000177 mapping = _multimap(kws, args[0])
178 else:
179 mapping = args[0]
Barry Warsaw46b629c2004-09-13 14:35:04 +0000180 # Helper function for .sub()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000181 def convert(mo):
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000182 named = mo.group('named')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000183 if named is not None:
184 try:
Barry Warsaw12827c12004-09-10 03:08:08 +0000185 # We use this idiom instead of str() because the latter
186 # will fail if val is a Unicode containing non-ASCII
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000187 return '%s' % (mapping[named],)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000188 except KeyError:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000189 return self.delimiter + named
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000190 braced = mo.group('braced')
Raymond Hettinger6d191112004-09-14 02:34:08 +0000191 if braced is not None:
192 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000193 return '%s' % (mapping[braced],)
Raymond Hettinger6d191112004-09-14 02:34:08 +0000194 except KeyError:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000195 return self.delimiter + '{' + braced + '}'
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000196 if mo.group('escaped') is not None:
Barry Warsaw17cb6002004-09-18 00:06:34 +0000197 return self.delimiter
Barry Warsawb5c6b5b2004-09-13 20:52:50 +0000198 if mo.group('invalid') is not None:
Barry Warsaw8c72eae2004-11-01 03:52:43 +0000199 return self.delimiter
Neal Norwitz6627a962004-10-17 16:27:18 +0000200 raise ValueError('Unrecognized named group in pattern',
201 self.pattern)
Barry Warsaw12827c12004-09-10 03:08:08 +0000202 return self.pattern.sub(convert, self.template)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000203
204
Raymond Hettinger57aef9c2004-12-07 07:55:07 +0000205
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000206####################################################################
Barry Warsaw8bee7612004-08-25 02:22:30 +0000207# NOTE: Everything below here is deprecated. Use string methods instead.
208# This stuff will go away in Python 3.0.
209
Guido van Rossum710c3521994-08-17 13:16:11 +0000210# Backward compatible names for exceptions
211index_error = ValueError
212atoi_error = ValueError
213atof_error = ValueError
214atol_error = ValueError
215
Guido van Rossumc6360141990-10-13 19:23:40 +0000216# convert UPPER CASE letters to lower case
217def lower(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000218 """lower(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000219
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000220 Return a copy of the string s converted to lowercase.
Guido van Rossum20032041997-12-29 19:26:28 +0000221
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000222 """
223 return s.lower()
Guido van Rossumc6360141990-10-13 19:23:40 +0000224
225# Convert lower case letters to UPPER CASE
226def upper(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000227 """upper(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000228
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000229 Return a copy of the string s converted to uppercase.
Guido van Rossum20032041997-12-29 19:26:28 +0000230
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000231 """
232 return s.upper()
Guido van Rossumc6360141990-10-13 19:23:40 +0000233
234# Swap lower case letters and UPPER CASE
235def swapcase(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000236 """swapcase(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000237
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000238 Return a copy of the string s with upper case characters
239 converted to lowercase and vice versa.
Guido van Rossum20032041997-12-29 19:26:28 +0000240
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000241 """
242 return s.swapcase()
Guido van Rossumc6360141990-10-13 19:23:40 +0000243
244# Strip leading and trailing tabs and spaces
Martin v. Löwis1f046102002-11-08 12:09:59 +0000245def strip(s, chars=None):
Neal Norwitza4864a22002-11-14 03:31:32 +0000246 """strip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000247
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000248 Return a copy of the string s with leading and trailing
249 whitespace removed.
Neal Norwitzffe33b72003-04-10 22:35:32 +0000250 If chars is given and not None, remove characters in chars instead.
Neal Norwitza4864a22002-11-14 03:31:32 +0000251 If chars is unicode, S will be converted to unicode before stripping.
Guido van Rossum20032041997-12-29 19:26:28 +0000252
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000253 """
Martin v. Löwis1f046102002-11-08 12:09:59 +0000254 return s.strip(chars)
Guido van Rossumc6360141990-10-13 19:23:40 +0000255
Guido van Rossum306a8a61996-08-08 18:40:59 +0000256# Strip leading tabs and spaces
Neal Norwitzffe33b72003-04-10 22:35:32 +0000257def lstrip(s, chars=None):
258 """lstrip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000259
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000260 Return a copy of the string s with leading whitespace removed.
Neal Norwitzffe33b72003-04-10 22:35:32 +0000261 If chars is given and not None, remove characters in chars instead.
Guido van Rossum20032041997-12-29 19:26:28 +0000262
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000263 """
Neal Norwitzffe33b72003-04-10 22:35:32 +0000264 return s.lstrip(chars)
Guido van Rossum306a8a61996-08-08 18:40:59 +0000265
266# Strip trailing tabs and spaces
Neal Norwitzffe33b72003-04-10 22:35:32 +0000267def rstrip(s, chars=None):
268 """rstrip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000269
Neal Norwitzffe33b72003-04-10 22:35:32 +0000270 Return a copy of the string s with trailing whitespace removed.
271 If chars is given and not None, remove characters in chars instead.
Guido van Rossum20032041997-12-29 19:26:28 +0000272
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000273 """
Neal Norwitzffe33b72003-04-10 22:35:32 +0000274 return s.rstrip(chars)
Guido van Rossum306a8a61996-08-08 18:40:59 +0000275
276
Guido van Rossumc6360141990-10-13 19:23:40 +0000277# Split a string into a list of space/tab-separated words
Guido van Rossum8f0c5a72000-03-10 23:22:10 +0000278def split(s, sep=None, maxsplit=-1):
Fred Drakee4f13661999-11-04 19:19:48 +0000279 """split(s [,sep [,maxsplit]]) -> list of strings
Guido van Rossum20032041997-12-29 19:26:28 +0000280
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000281 Return a list of the words in the string s, using sep as the
Fred Drake14537542002-01-30 16:15:13 +0000282 delimiter string. If maxsplit is given, splits at no more than
283 maxsplit places (resulting in at most maxsplit+1 words). If sep
Walter Dörwald065a32f2004-09-14 09:45:10 +0000284 is not specified or is None, any whitespace string is a separator.
Guido van Rossum20032041997-12-29 19:26:28 +0000285
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000286 (split and splitfields are synonymous)
Guido van Rossum20032041997-12-29 19:26:28 +0000287
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000288 """
289 return s.split(sep, maxsplit)
290splitfields = split
Guido van Rossumfac38b71991-04-07 13:42:19 +0000291
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000292# Split a string into a list of space/tab-separated words
293def rsplit(s, sep=None, maxsplit=-1):
294 """rsplit(s [,sep [,maxsplit]]) -> list of strings
295
296 Return a list of the words in the string s, using sep as the
297 delimiter string, starting at the end of the string and working
298 to the front. If maxsplit is given, at most maxsplit splits are
299 done. If sep is not specified or is None, any whitespace string
300 is a separator.
301 """
302 return s.rsplit(sep, maxsplit)
303
Guido van Rossum2ab19921995-06-22 18:58:00 +0000304# Join fields with optional separator
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000305def join(words, sep = ' '):
306 """join(list [,sep]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000307
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000308 Return a string composed of the words in list, with
Thomas Wouters7e474022000-07-16 12:04:32 +0000309 intervening occurrences of sep. The default separator is a
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000310 single space.
Guido van Rossum20032041997-12-29 19:26:28 +0000311
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000312 (joinfields and join are synonymous)
Guido van Rossum20032041997-12-29 19:26:28 +0000313
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000314 """
315 return sep.join(words)
316joinfields = join
317
Guido van Rossumd3166071993-05-24 14:16:22 +0000318# Find substring, raise exception if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000319def index(s, *args):
320 """index(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000321
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000322 Like find but raises ValueError when the substring is not found.
Guido van Rossum20032041997-12-29 19:26:28 +0000323
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000324 """
Fred Drake046d2722000-07-03 07:23:13 +0000325 return s.index(*args)
Guido van Rossumd3166071993-05-24 14:16:22 +0000326
Guido van Rossume65cce51993-11-08 15:05:21 +0000327# Find last substring, raise exception if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000328def rindex(s, *args):
329 """rindex(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000330
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000331 Like rfind but raises ValueError when the substring is not found.
Guido van Rossum20032041997-12-29 19:26:28 +0000332
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000333 """
Fred Drake046d2722000-07-03 07:23:13 +0000334 return s.rindex(*args)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000335
336# Count non-overlapping occurrences of substring
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000337def count(s, *args):
338 """count(s, sub[, start[,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000339
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000340 Return the number of occurrences of substring sub in string
341 s[start:end]. Optional arguments start and end are
342 interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000343
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000344 """
Fred Drake046d2722000-07-03 07:23:13 +0000345 return s.count(*args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000346
Guido van Rossumd3166071993-05-24 14:16:22 +0000347# Find substring, return -1 if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000348def find(s, *args):
349 """find(s, sub [,start [,end]]) -> in
Guido van Rossum20032041997-12-29 19:26:28 +0000350
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000351 Return the lowest index in s where substring sub is found,
352 such that sub is contained within s[start,end]. Optional
353 arguments start and end are interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000354
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000355 Return -1 on failure.
Guido van Rossum20032041997-12-29 19:26:28 +0000356
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000357 """
Fred Drake046d2722000-07-03 07:23:13 +0000358 return s.find(*args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000359
Guido van Rossume65cce51993-11-08 15:05:21 +0000360# Find last substring, return -1 if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000361def rfind(s, *args):
362 """rfind(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000363
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000364 Return the highest index in s where substring sub is found,
365 such that sub is contained within s[start,end]. Optional
366 arguments start and end are interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000367
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000368 Return -1 on failure.
Guido van Rossum20032041997-12-29 19:26:28 +0000369
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000370 """
Fred Drake046d2722000-07-03 07:23:13 +0000371 return s.rfind(*args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000372
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000373# for a bit of speed
374_float = float
375_int = int
Guido van Rossume2a383d2007-01-15 16:59:06 +0000376_long = int
Guido van Rossumd0753e21997-12-10 22:59:55 +0000377
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000378# Convert string to float
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000379def atof(s):
380 """atof(s) -> float
Guido van Rossum20032041997-12-29 19:26:28 +0000381
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000382 Return the floating point number represented by the string s.
Guido van Rossum20032041997-12-29 19:26:28 +0000383
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000384 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000385 return _float(s)
386
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000387
Guido van Rossumc6360141990-10-13 19:23:40 +0000388# Convert string to integer
Guido van Rossum9e896b32000-04-05 20:11:21 +0000389def atoi(s , base=10):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000390 """atoi(s [,base]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000391
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000392 Return the integer represented by the string s in the given
393 base, which defaults to 10. The string s must consist of one
394 or more digits, possibly preceded by a sign. If base is 0, it
395 is chosen from the leading characters of s, 0 for octal, 0x or
396 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
397 accepted.
Guido van Rossum20032041997-12-29 19:26:28 +0000398
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000399 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000400 return _int(s, base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000401
Guido van Rossumc6360141990-10-13 19:23:40 +0000402
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000403# Convert string to long integer
Guido van Rossum9e896b32000-04-05 20:11:21 +0000404def atol(s, base=10):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000405 """atol(s [,base]) -> long
Guido van Rossum20032041997-12-29 19:26:28 +0000406
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000407 Return the long integer represented by the string s in the
408 given base, which defaults to 10. The string s must consist
409 of one or more digits, possibly preceded by a sign. If base
410 is 0, it is chosen from the leading characters of s, 0 for
411 octal, 0x or 0X for hexadecimal. If base is 16, a preceding
412 0x or 0X is accepted. A trailing L or l is not accepted,
413 unless base is 0.
Guido van Rossum20032041997-12-29 19:26:28 +0000414
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000415 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000416 return _long(s, base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000417
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000418
Guido van Rossumc6360141990-10-13 19:23:40 +0000419# Left-justify a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000420def ljust(s, width, *args):
421 """ljust(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000422
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000423 Return a left-justified version of s, in a field of the
424 specified width, padded with spaces as needed. The string is
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000425 never truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000426
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000427 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000428 return s.ljust(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000429
430# Right-justify a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000431def rjust(s, width, *args):
432 """rjust(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000433
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000434 Return a right-justified version of s, in a field of the
435 specified width, padded with spaces as needed. The string is
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000436 never truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000437
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000438 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000439 return s.rjust(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000440
441# Center a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000442def center(s, width, *args):
443 """center(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000444
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000445 Return a center version of s, in a field of the specified
446 width. padded with spaces as needed. The string is never
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000447 truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000448
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000449 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000450 return s.center(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000451
452# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
453# Decadent feature: the argument may be a string or a number
454# (Use of this is deprecated; it should be a string as with ljust c.s.)
455def zfill(x, width):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000456 """zfill(x, width) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000457
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000458 Pad a numeric string x with zeros on the left, to fill a field
459 of the specified width. The string x is never truncated.
Guido van Rossum20032041997-12-29 19:26:28 +0000460
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000461 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000462 if not isinstance(x, basestring):
Walter Dörwald068325e2002-04-15 13:36:47 +0000463 x = repr(x)
464 return x.zfill(width)
Guido van Rossum6ff2e901992-03-27 15:13:31 +0000465
466# Expand tabs in a string.
467# Doesn't take non-printing chars into account, but does understand \n.
Guido van Rossum894a7bb1995-08-10 19:42:05 +0000468def expandtabs(s, tabsize=8):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000469 """expandtabs(s [,tabsize]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000470
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000471 Return a copy of the string s with all tab characters replaced
472 by the appropriate number of spaces, depending on the current
473 column, and the tabsize (default 8).
Guido van Rossum20032041997-12-29 19:26:28 +0000474
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000475 """
Fred Drake046d2722000-07-03 07:23:13 +0000476 return s.expandtabs(tabsize)
Guido van Rossum2db91351992-10-18 17:09:59 +0000477
Guido van Rossum25395281996-05-28 23:08:45 +0000478# Character translation through look-up table.
Guido van Rossumed7253c1996-07-23 18:12:39 +0000479def translate(s, table, deletions=""):
Guido van Rossum5aff7752000-12-19 02:39:08 +0000480 """translate(s,table [,deletions]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000481
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000482 Return a copy of the string s, where all characters occurring
Guido van Rossum5aff7752000-12-19 02:39:08 +0000483 in the optional argument deletions are removed, and the
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000484 remaining characters have been mapped through the given
Guido van Rossum5aff7752000-12-19 02:39:08 +0000485 translation table, which must be a string of length 256. The
486 deletions argument is not allowed for Unicode strings.
Guido van Rossum20032041997-12-29 19:26:28 +0000487
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000488 """
Guido van Rossum5aff7752000-12-19 02:39:08 +0000489 if deletions:
490 return s.translate(table, deletions)
491 else:
492 # Add s[:0] so that if s is Unicode and table is an 8-bit string,
493 # table is converted to Unicode. This means that table *cannot*
494 # be a dictionary -- for that feature, use u.translate() directly.
495 return s.translate(table + s[:0])
Guido van Rossum2db91351992-10-18 17:09:59 +0000496
Guido van Rossum8775d8b1996-06-11 18:43:00 +0000497# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
498def capitalize(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000499 """capitalize(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000500
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000501 Return a copy of the string s with only its first character
502 capitalized.
Guido van Rossum20032041997-12-29 19:26:28 +0000503
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000504 """
505 return s.capitalize()
Guido van Rossum8775d8b1996-06-11 18:43:00 +0000506
Guido van Rossum1eb9a811997-03-25 16:50:31 +0000507# Substring replacement (global)
Guido van Rossum8f0c5a72000-03-10 23:22:10 +0000508def replace(s, old, new, maxsplit=-1):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000509 """replace (str, old, new[, maxsplit]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000510
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000511 Return a copy of string str with all occurrences of substring
512 old replaced by new. If the optional argument maxsplit is
513 given, only the first maxsplit occurrences are replaced.
Guido van Rossum20032041997-12-29 19:26:28 +0000514
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000515 """
516 return s.replace(old, new, maxsplit)
Guido van Rossum1eb9a811997-03-25 16:50:31 +0000517
518
Guido van Rossum2db91351992-10-18 17:09:59 +0000519# Try importing optional built-in module "strop" -- if it exists,
520# it redefines some string operations that are 100-1000 times faster.
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000521# It also defines values for whitespace, lowercase and uppercase
522# that match <ctype.h>'s definitions.
Guido van Rossum2db91351992-10-18 17:09:59 +0000523
524try:
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000525 from strop import maketrans, lowercase, uppercase, whitespace
526 letters = lowercase + uppercase
Guido van Rossumb6775db1994-08-01 11:34:53 +0000527except ImportError:
Fred Drake857c4c32000-02-10 16:21:11 +0000528 pass # Use the original versions