blob: 9965111144aac25330236634ea7071dbcb4c82ae [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
Barry Warsaw8bee7612004-08-25 02:22:30 +000038# Note that Cookie.py bogusly uses _idmap :(
Martin v. Löwis5357c652002-10-14 20:03:40 +000039l = map(chr, xrange(256))
40_idmap = str('').join(l)
41del l
Guido van Rossumc6360141990-10-13 19:23:40 +000042
Barry Warsaw8bee7612004-08-25 02:22:30 +000043# Functions which aren't available as string methods.
44
45# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
46# See also regsub.capwords().
47def capwords(s, sep=None):
48 """capwords(s, [sep]) -> string
49
50 Split the argument into words using split, capitalize each
51 word using capitalize, and join the capitalized words using
52 join. Note that this replaces runs of whitespace characters by
53 a single space.
54
55 """
56 return (sep or ' ').join([x.capitalize() for x in s.split(sep)])
57
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:
73 _idmapL = map(None, _idmap)
74 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
81
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +000082####################################################################
Barry Warsaw8bee7612004-08-25 02:22:30 +000083import re as _re
84
85class Template(unicode):
86 """A string class for supporting $-substitutions."""
87 __slots__ = []
88
89 # Search for $$, $identifier, ${identifier}, and any bare $'s
90 pattern = _re.compile(r"""
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +000091 (?P<escaped>\${2})| # Escape sequence of two $ signs
92 \$(?P<named>[_a-z][_a-z0-9]*)| # $ and a Python identifier
93 \${(?P<braced>[_a-z][_a-z0-9]*)}| # $ and a brace delimited identifier
94 (?P<bogus>\$) # Other ill-formed $ expressions
95 """, _re.IGNORECASE | _re.VERBOSE)
Barry Warsaw8bee7612004-08-25 02:22:30 +000096
97 def __mod__(self, mapping):
98 def convert(mo):
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +000099 if mo.group('escaped') is not None:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000100 return '$'
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000101 if mo.group('bogus') is not None:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000102 raise ValueError('Invalid placeholder at index %d' %
103 mo.start('bogus'))
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000104 val = mapping[mo.group('named') or mo.group('braced')]
Barry Warsaw8bee7612004-08-25 02:22:30 +0000105 return unicode(val)
106 return self.pattern.sub(convert, self)
107
108
109class SafeTemplate(Template):
110 """A string class for supporting $-substitutions.
111
112 This class is 'safe' in the sense that you will never get KeyErrors if
113 there are placeholders missing from the interpolation dictionary. In that
114 case, you will get the original placeholder in the value string.
115 """
116 __slots__ = []
117
118 def __mod__(self, mapping):
119 def convert(mo):
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000120 if mo.group('escaped') is not None:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000121 return '$'
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000122 if mo.group('bogus') is not None:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000123 raise ValueError('Invalid placeholder at index %d' %
124 mo.start('bogus'))
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000125 named = mo.group('named')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000126 if named is not None:
127 try:
128 return unicode(mapping[named])
129 except KeyError:
130 return '$' + named
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000131 braced = mo.group('braced')
Barry Warsaw8bee7612004-08-25 02:22:30 +0000132 try:
133 return unicode(mapping[braced])
134 except KeyError:
135 return '${' + braced + '}'
136 return self.pattern.sub(convert, self)
137
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000138del _re
Barry Warsaw8bee7612004-08-25 02:22:30 +0000139
140
Raymond Hettinger0d58e2b2004-08-26 00:21:13 +0000141####################################################################
Barry Warsaw8bee7612004-08-25 02:22:30 +0000142# NOTE: Everything below here is deprecated. Use string methods instead.
143# This stuff will go away in Python 3.0.
144
Guido van Rossum710c3521994-08-17 13:16:11 +0000145# Backward compatible names for exceptions
146index_error = ValueError
147atoi_error = ValueError
148atof_error = ValueError
149atol_error = ValueError
150
Guido van Rossumc6360141990-10-13 19:23:40 +0000151# convert UPPER CASE letters to lower case
152def lower(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000153 """lower(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000154
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000155 Return a copy of the string s converted to lowercase.
Guido van Rossum20032041997-12-29 19:26:28 +0000156
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000157 """
158 return s.lower()
Guido van Rossumc6360141990-10-13 19:23:40 +0000159
160# Convert lower case letters to UPPER CASE
161def upper(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000162 """upper(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000163
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000164 Return a copy of the string s converted to uppercase.
Guido van Rossum20032041997-12-29 19:26:28 +0000165
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000166 """
167 return s.upper()
Guido van Rossumc6360141990-10-13 19:23:40 +0000168
169# Swap lower case letters and UPPER CASE
170def swapcase(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171 """swapcase(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000172
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000173 Return a copy of the string s with upper case characters
174 converted to lowercase and vice versa.
Guido van Rossum20032041997-12-29 19:26:28 +0000175
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000176 """
177 return s.swapcase()
Guido van Rossumc6360141990-10-13 19:23:40 +0000178
179# Strip leading and trailing tabs and spaces
Martin v. Löwis1f046102002-11-08 12:09:59 +0000180def strip(s, chars=None):
Neal Norwitza4864a22002-11-14 03:31:32 +0000181 """strip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000182
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000183 Return a copy of the string s with leading and trailing
184 whitespace removed.
Neal Norwitzffe33b72003-04-10 22:35:32 +0000185 If chars is given and not None, remove characters in chars instead.
Neal Norwitza4864a22002-11-14 03:31:32 +0000186 If chars is unicode, S will be converted to unicode before stripping.
Guido van Rossum20032041997-12-29 19:26:28 +0000187
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188 """
Martin v. Löwis1f046102002-11-08 12:09:59 +0000189 return s.strip(chars)
Guido van Rossumc6360141990-10-13 19:23:40 +0000190
Guido van Rossum306a8a61996-08-08 18:40:59 +0000191# Strip leading tabs and spaces
Neal Norwitzffe33b72003-04-10 22:35:32 +0000192def lstrip(s, chars=None):
193 """lstrip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000194
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000195 Return a copy of the string s with leading whitespace removed.
Neal Norwitzffe33b72003-04-10 22:35:32 +0000196 If chars is given and not None, remove characters in chars instead.
Guido van Rossum20032041997-12-29 19:26:28 +0000197
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000198 """
Neal Norwitzffe33b72003-04-10 22:35:32 +0000199 return s.lstrip(chars)
Guido van Rossum306a8a61996-08-08 18:40:59 +0000200
201# Strip trailing tabs and spaces
Neal Norwitzffe33b72003-04-10 22:35:32 +0000202def rstrip(s, chars=None):
203 """rstrip(s [,chars]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000204
Neal Norwitzffe33b72003-04-10 22:35:32 +0000205 Return a copy of the string s with trailing whitespace removed.
206 If chars is given and not None, remove characters in chars instead.
Guido van Rossum20032041997-12-29 19:26:28 +0000207
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000208 """
Neal Norwitzffe33b72003-04-10 22:35:32 +0000209 return s.rstrip(chars)
Guido van Rossum306a8a61996-08-08 18:40:59 +0000210
211
Guido van Rossumc6360141990-10-13 19:23:40 +0000212# Split a string into a list of space/tab-separated words
Guido van Rossum8f0c5a72000-03-10 23:22:10 +0000213def split(s, sep=None, maxsplit=-1):
Fred Drakee4f13661999-11-04 19:19:48 +0000214 """split(s [,sep [,maxsplit]]) -> list of strings
Guido van Rossum20032041997-12-29 19:26:28 +0000215
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000216 Return a list of the words in the string s, using sep as the
Fred Drake14537542002-01-30 16:15:13 +0000217 delimiter string. If maxsplit is given, splits at no more than
218 maxsplit places (resulting in at most maxsplit+1 words). If sep
219 is not specified, any whitespace string is a separator.
Guido van Rossum20032041997-12-29 19:26:28 +0000220
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000221 (split and splitfields are synonymous)
Guido van Rossum20032041997-12-29 19:26:28 +0000222
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000223 """
224 return s.split(sep, maxsplit)
225splitfields = split
Guido van Rossumfac38b71991-04-07 13:42:19 +0000226
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000227# Split a string into a list of space/tab-separated words
228def rsplit(s, sep=None, maxsplit=-1):
229 """rsplit(s [,sep [,maxsplit]]) -> list of strings
230
231 Return a list of the words in the string s, using sep as the
232 delimiter string, starting at the end of the string and working
233 to the front. If maxsplit is given, at most maxsplit splits are
234 done. If sep is not specified or is None, any whitespace string
235 is a separator.
236 """
237 return s.rsplit(sep, maxsplit)
238
Guido van Rossum2ab19921995-06-22 18:58:00 +0000239# Join fields with optional separator
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000240def join(words, sep = ' '):
241 """join(list [,sep]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000242
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000243 Return a string composed of the words in list, with
Thomas Wouters7e474022000-07-16 12:04:32 +0000244 intervening occurrences of sep. The default separator is a
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000245 single space.
Guido van Rossum20032041997-12-29 19:26:28 +0000246
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000247 (joinfields and join are synonymous)
Guido van Rossum20032041997-12-29 19:26:28 +0000248
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000249 """
250 return sep.join(words)
251joinfields = join
252
Guido van Rossumd3166071993-05-24 14:16:22 +0000253# Find substring, raise exception if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000254def index(s, *args):
255 """index(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000256
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000257 Like find but raises ValueError when the substring is not found.
Guido van Rossum20032041997-12-29 19:26:28 +0000258
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000259 """
Fred Drake046d2722000-07-03 07:23:13 +0000260 return s.index(*args)
Guido van Rossumd3166071993-05-24 14:16:22 +0000261
Guido van Rossume65cce51993-11-08 15:05:21 +0000262# Find last substring, raise exception if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000263def rindex(s, *args):
264 """rindex(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000265
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000266 Like rfind but raises ValueError when the substring is not found.
Guido van Rossum20032041997-12-29 19:26:28 +0000267
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000268 """
Fred Drake046d2722000-07-03 07:23:13 +0000269 return s.rindex(*args)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270
271# Count non-overlapping occurrences of substring
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000272def count(s, *args):
273 """count(s, sub[, start[,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000274
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000275 Return the number of occurrences of substring sub in string
276 s[start:end]. Optional arguments start and end are
277 interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000278
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000279 """
Fred Drake046d2722000-07-03 07:23:13 +0000280 return s.count(*args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000281
Guido van Rossumd3166071993-05-24 14:16:22 +0000282# Find substring, return -1 if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000283def find(s, *args):
284 """find(s, sub [,start [,end]]) -> in
Guido van Rossum20032041997-12-29 19:26:28 +0000285
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000286 Return the lowest index in s where substring sub is found,
287 such that sub is contained within s[start,end]. Optional
288 arguments start and end are interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000289
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000290 Return -1 on failure.
Guido van Rossum20032041997-12-29 19:26:28 +0000291
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000292 """
Fred Drake046d2722000-07-03 07:23:13 +0000293 return s.find(*args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000294
Guido van Rossume65cce51993-11-08 15:05:21 +0000295# Find last substring, return -1 if not found
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000296def rfind(s, *args):
297 """rfind(s, sub [,start [,end]]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000298
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000299 Return the highest index in s where substring sub is found,
300 such that sub is contained within s[start,end]. Optional
301 arguments start and end are interpreted as in slice notation.
Guido van Rossum20032041997-12-29 19:26:28 +0000302
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000303 Return -1 on failure.
Guido van Rossum20032041997-12-29 19:26:28 +0000304
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000305 """
Fred Drake046d2722000-07-03 07:23:13 +0000306 return s.rfind(*args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000307
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000308# for a bit of speed
309_float = float
310_int = int
311_long = long
Guido van Rossumd0753e21997-12-10 22:59:55 +0000312
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000313# Convert string to float
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000314def atof(s):
315 """atof(s) -> float
Guido van Rossum20032041997-12-29 19:26:28 +0000316
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000317 Return the floating point number represented by the string s.
Guido van Rossum20032041997-12-29 19:26:28 +0000318
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000319 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000320 return _float(s)
321
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000322
Guido van Rossumc6360141990-10-13 19:23:40 +0000323# Convert string to integer
Guido van Rossum9e896b32000-04-05 20:11:21 +0000324def atoi(s , base=10):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000325 """atoi(s [,base]) -> int
Guido van Rossum20032041997-12-29 19:26:28 +0000326
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000327 Return the integer represented by the string s in the given
328 base, which defaults to 10. The string s must consist of one
329 or more digits, possibly preceded by a sign. If base is 0, it
330 is chosen from the leading characters of s, 0 for octal, 0x or
331 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
332 accepted.
Guido van Rossum20032041997-12-29 19:26:28 +0000333
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000334 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000335 return _int(s, base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000336
Guido van Rossumc6360141990-10-13 19:23:40 +0000337
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000338# Convert string to long integer
Guido van Rossum9e896b32000-04-05 20:11:21 +0000339def atol(s, base=10):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000340 """atol(s [,base]) -> long
Guido van Rossum20032041997-12-29 19:26:28 +0000341
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000342 Return the long integer represented by the string s in the
343 given base, which defaults to 10. The string s must consist
344 of one or more digits, possibly preceded by a sign. If base
345 is 0, it is chosen from the leading characters of s, 0 for
346 octal, 0x or 0X for hexadecimal. If base is 16, a preceding
347 0x or 0X is accepted. A trailing L or l is not accepted,
348 unless base is 0.
Guido van Rossum20032041997-12-29 19:26:28 +0000349
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000350 """
Guido van Rossum9e896b32000-04-05 20:11:21 +0000351 return _long(s, base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000352
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000353
Guido van Rossumc6360141990-10-13 19:23:40 +0000354# Left-justify a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000355def ljust(s, width, *args):
356 """ljust(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000357
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000358 Return a left-justified version of s, in a field of the
359 specified width, padded with spaces as needed. The string is
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000360 never truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000361
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000362 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000363 return s.ljust(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000364
365# Right-justify a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000366def rjust(s, width, *args):
367 """rjust(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000368
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000369 Return a right-justified version of s, in a field of the
370 specified width, padded with spaces as needed. The string is
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000371 never truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000372
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000373 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000374 return s.rjust(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000375
376# Center a string
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000377def center(s, width, *args):
378 """center(s, width[, fillchar]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000379
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000380 Return a center version of s, in a field of the specified
381 width. padded with spaces as needed. The string is never
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000382 truncated. If specified the fillchar is used instead of spaces.
Guido van Rossum20032041997-12-29 19:26:28 +0000383
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000384 """
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000385 return s.center(width, *args)
Guido van Rossumc6360141990-10-13 19:23:40 +0000386
387# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
388# Decadent feature: the argument may be a string or a number
389# (Use of this is deprecated; it should be a string as with ljust c.s.)
390def zfill(x, width):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000391 """zfill(x, width) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000392
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000393 Pad a numeric string x with zeros on the left, to fill a field
394 of the specified width. The string x is never truncated.
Guido van Rossum20032041997-12-29 19:26:28 +0000395
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000396 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000397 if not isinstance(x, basestring):
Walter Dörwald068325e2002-04-15 13:36:47 +0000398 x = repr(x)
399 return x.zfill(width)
Guido van Rossum6ff2e901992-03-27 15:13:31 +0000400
401# Expand tabs in a string.
402# Doesn't take non-printing chars into account, but does understand \n.
Guido van Rossum894a7bb1995-08-10 19:42:05 +0000403def expandtabs(s, tabsize=8):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000404 """expandtabs(s [,tabsize]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000405
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000406 Return a copy of the string s with all tab characters replaced
407 by the appropriate number of spaces, depending on the current
408 column, and the tabsize (default 8).
Guido van Rossum20032041997-12-29 19:26:28 +0000409
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000410 """
Fred Drake046d2722000-07-03 07:23:13 +0000411 return s.expandtabs(tabsize)
Guido van Rossum2db91351992-10-18 17:09:59 +0000412
Guido van Rossum25395281996-05-28 23:08:45 +0000413# Character translation through look-up table.
Guido van Rossumed7253c1996-07-23 18:12:39 +0000414def translate(s, table, deletions=""):
Guido van Rossum5aff7752000-12-19 02:39:08 +0000415 """translate(s,table [,deletions]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000416
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000417 Return a copy of the string s, where all characters occurring
Guido van Rossum5aff7752000-12-19 02:39:08 +0000418 in the optional argument deletions are removed, and the
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000419 remaining characters have been mapped through the given
Guido van Rossum5aff7752000-12-19 02:39:08 +0000420 translation table, which must be a string of length 256. The
421 deletions argument is not allowed for Unicode strings.
Guido van Rossum20032041997-12-29 19:26:28 +0000422
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000423 """
Guido van Rossum5aff7752000-12-19 02:39:08 +0000424 if deletions:
425 return s.translate(table, deletions)
426 else:
427 # Add s[:0] so that if s is Unicode and table is an 8-bit string,
428 # table is converted to Unicode. This means that table *cannot*
429 # be a dictionary -- for that feature, use u.translate() directly.
430 return s.translate(table + s[:0])
Guido van Rossum2db91351992-10-18 17:09:59 +0000431
Guido van Rossum8775d8b1996-06-11 18:43:00 +0000432# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
433def capitalize(s):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000434 """capitalize(s) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000435
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000436 Return a copy of the string s with only its first character
437 capitalized.
Guido van Rossum20032041997-12-29 19:26:28 +0000438
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000439 """
440 return s.capitalize()
Guido van Rossum8775d8b1996-06-11 18:43:00 +0000441
Guido van Rossum1eb9a811997-03-25 16:50:31 +0000442# Substring replacement (global)
Guido van Rossum8f0c5a72000-03-10 23:22:10 +0000443def replace(s, old, new, maxsplit=-1):
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000444 """replace (str, old, new[, maxsplit]) -> string
Guido van Rossum20032041997-12-29 19:26:28 +0000445
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000446 Return a copy of string str with all occurrences of substring
447 old replaced by new. If the optional argument maxsplit is
448 given, only the first maxsplit occurrences are replaced.
Guido van Rossum20032041997-12-29 19:26:28 +0000449
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000450 """
451 return s.replace(old, new, maxsplit)
Guido van Rossum1eb9a811997-03-25 16:50:31 +0000452
453
Guido van Rossum2db91351992-10-18 17:09:59 +0000454# Try importing optional built-in module "strop" -- if it exists,
455# it redefines some string operations that are 100-1000 times faster.
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000456# It also defines values for whitespace, lowercase and uppercase
457# that match <ctype.h>'s definitions.
Guido van Rossum2db91351992-10-18 17:09:59 +0000458
459try:
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000460 from strop import maketrans, lowercase, uppercase, whitespace
461 letters = lowercase + uppercase
Guido van Rossumb6775db1994-08-01 11:34:53 +0000462except ImportError:
Fred Drake857c4c32000-02-10 16:21:11 +0000463 pass # Use the original versions