1 # module 'string' -- A collection of string operations
3 # Warning: most of the code you see here isn't normally used nowadays. With
4 # Python 1.6, many of these functions are implemented as methods on the
5 # standard string object. They used to be implemented by a built-in module
6 # called strop, but strop is now obsolete itself.
8 """Common string manipulations.
10 Public module variables:
12 whitespace -- a string containing all characters considered whitespace
13 lowercase -- a string containing all characters considered lowercase letters
14 uppercase -- a string containing all characters considered uppercase letters
15 letters -- a string containing all characters considered letters
16 digits -- a string containing all characters considered decimal digits
17 hexdigits -- a string containing all characters considered hexadecimal digits
18 octdigits -- a string containing all characters considered octal digits
22 # Some strings for ctype-style character classification
23 whitespace
= ' \t\n\r\v\f'
24 lowercase
= 'abcdefghijklmnopqrstuvwxyz'
25 uppercase
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
26 letters
= lowercase
+ uppercase
28 hexdigits
= digits
+ 'abcdef' + 'ABCDEF'
29 octdigits
= '01234567'
31 # Case conversion helpers
33 for i
in range(256): _idmap
= _idmap
+ chr(i
)
36 # Backward compatible names for exceptions
37 index_error
= ValueError
38 atoi_error
= ValueError
39 atof_error
= ValueError
40 atol_error
= ValueError
42 # convert UPPER CASE letters to lower case
46 Return a copy of the string s converted to lowercase.
51 # Convert lower case letters to UPPER CASE
55 Return a copy of the string s converted to uppercase.
60 # Swap lower case letters and UPPER CASE
62 """swapcase(s) -> string
64 Return a copy of the string s with upper case characters
65 converted to lowercase and vice versa.
70 # Strip leading and trailing tabs and spaces
74 Return a copy of the string s with leading and trailing
80 # Strip leading tabs and spaces
82 """lstrip(s) -> string
84 Return a copy of the string s with leading whitespace removed.
89 # Strip trailing tabs and spaces
91 """rstrip(s) -> string
93 Return a copy of the string s with trailing whitespace
100 # Split a string into a list of space/tab-separated words
101 # NB: split(s) is NOT the same as splitfields(s, ' ')!
102 def split(s
, sep
=None, maxsplit
=0):
103 """split(str [,sep [,maxsplit]]) -> list of strings
105 Return a list of the words in the string s, using sep as the
106 delimiter string. If maxsplit is nonzero, splits into at most
107 maxsplit words If sep is not specified, any whitespace string
108 is a separator. Maxsplit defaults to 0.
110 (split and splitfields are synonymous)
113 return s
.split(sep
, maxsplit
)
116 # Join fields with optional separator
117 def join(words
, sep
= ' '):
118 """join(list [,sep]) -> string
120 Return a string composed of the words in list, with
121 intervening occurences of sep. The default separator is a
124 (joinfields and join are synonymous)
127 return sep
.join(words
)
130 # for a little bit of speed
133 # Find substring, raise exception if not found
135 """index(s, sub [,start [,end]]) -> int
137 Like find but raises ValueError when the substring is not found.
140 return _apply(s
.index
, args
)
142 # Find last substring, raise exception if not found
143 def rindex(s
, *args
):
144 """rindex(s, sub [,start [,end]]) -> int
146 Like rfind but raises ValueError when the substring is not found.
149 return _apply(s
.rindex
, args
)
151 # Count non-overlapping occurrences of substring
153 """count(s, sub[, start[,end]]) -> int
155 Return the number of occurrences of substring sub in string
156 s[start:end]. Optional arguments start and end are
157 interpreted as in slice notation.
160 return _apply(s
.count
, args
)
162 # Find substring, return -1 if not found
164 """find(s, sub [,start [,end]]) -> in
166 Return the lowest index in s where substring sub is found,
167 such that sub is contained within s[start,end]. Optional
168 arguments start and end are interpreted as in slice notation.
170 Return -1 on failure.
173 return _apply(s
.find
, args
)
175 # Find last substring, return -1 if not found
177 """rfind(s, sub [,start [,end]]) -> int
179 Return the highest index in s where substring sub is found,
180 such that sub is contained within s[start,end]. Optional
181 arguments start and end are interpreted as in slice notation.
183 Return -1 on failure.
186 return _apply(s
.rfind
, args
)
192 _StringType
= type('')
194 # Convert string to float
198 Return the floating point number represented by the string s.
201 if type(s
) == _StringType
:
204 raise TypeError('argument 1: expected string, %s found' %
207 # Convert string to integer
209 """atoi(s [,base]) -> int
211 Return the integer represented by the string s in the given
212 base, which defaults to 10. The string s must consist of one
213 or more digits, possibly preceded by a sign. If base is 0, it
214 is chosen from the leading characters of s, 0 for octal, 0x or
215 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
222 raise TypeError('function requires at least 1 argument: %d given' %
224 # Don't catch type error resulting from too many arguments to int(). The
225 # error message isn't compatible but the error type is, and this function
226 # is complicated enough already.
227 if type(s
) == _StringType
:
228 return _apply(_int
, args
)
230 raise TypeError('argument 1: expected string, %s found' %
234 # Convert string to long integer
236 """atol(s [,base]) -> long
238 Return the long integer represented by the string s in the
239 given base, which defaults to 10. The string s must consist
240 of one or more digits, possibly preceded by a sign. If base
241 is 0, it is chosen from the leading characters of s, 0 for
242 octal, 0x or 0X for hexadecimal. If base is 16, a preceding
243 0x or 0X is accepted. A trailing L or l is not accepted,
250 raise TypeError('function requires at least 1 argument: %d given' %
252 # Don't catch type error resulting from too many arguments to long(). The
253 # error message isn't compatible but the error type is, and this function
254 # is complicated enough already.
255 if type(s
) == _StringType
:
256 return _apply(_long
, args
)
258 raise TypeError('argument 1: expected string, %s found' %
262 # Left-justify a string
264 """ljust(s, width) -> string
266 Return a left-justified version of s, in a field of the
267 specified width, padded with spaces as needed. The string is
275 # Right-justify a string
277 """rjust(s, width) -> string
279 Return a right-justified version of s, in a field of the
280 specified width, padded with spaces as needed. The string is
289 def center(s
, width
):
290 """center(s, width) -> string
292 Return a center version of s, in a field of the specified
293 width. padded with spaces as needed. The string is never
301 # This ensures that center(center(s, i), j) = center(s, j)
303 return ' '*half
+ s
+ ' '*(n
-half
)
305 # Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
306 # Decadent feature: the argument may be a string or a number
307 # (Use of this is deprecated; it should be a string as with ljust c.s.)
309 """zfill(x, width) -> string
311 Pad a numeric string x with zeros on the left, to fill a field
312 of the specified width. The string x is never truncated.
315 if type(x
) == type(''): s
= x
318 if n
>= width
: return s
320 if s
[0] in ('-', '+'):
321 sign
, s
= s
[0], s
[1:]
322 return sign
+ '0'*(width
-n
) + s
324 # Expand tabs in a string.
325 # Doesn't take non-printing chars into account, but does understand \n.
326 def expandtabs(s
, tabsize
=8):
327 """expandtabs(s [,tabsize]) -> string
329 Return a copy of the string s with all tab characters replaced
330 by the appropriate number of spaces, depending on the current
331 column, and the tabsize (default 8).
337 c
= ' '*(tabsize
- len(line
) % tabsize
)
344 # Character translation through look-up table.
345 def translate(s
, table
, deletions
=""):
346 """translate(s,table [,deletechars]) -> string
348 Return a copy of the string s, where all characters occurring
349 in the optional argument deletechars are removed, and the
350 remaining characters have been mapped through the given
351 translation table, which must be a string of length 256.
354 return s
.translate(table
, deletions
)
356 # Capitalize a string, e.g. "aBc dEf" -> "Abc def".
358 """capitalize(s) -> string
360 Return a copy of the string s with only its first character
364 return s
.capitalize()
366 # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
367 # See also regsub.capwords().
368 def capwords(s
, sep
=None):
369 """capwords(s, [sep]) -> string
371 Split the argument into words using split, capitalize each
372 word using capitalize, and join the capitalized words using
373 join. Note that this replaces runs of whitespace characters by
377 return join(map(capitalize
, s
.split(sep
)), sep
or ' ')
379 # Construct a translation string
381 def maketrans(fromstr
, tostr
):
382 """maketrans(frm, to) -> string
384 Return a translation table (a string of 256 bytes long)
385 suitable for use in string.translate. The strings frm and to
386 must be of the same length.
389 if len(fromstr
) != len(tostr
):
390 raise ValueError, "maketrans arguments must have same length"
393 _idmapL
= map(None, _idmap
)
395 fromstr
= map(ord, fromstr
)
396 for i
in range(len(fromstr
)):
397 L
[fromstr
[i
]] = tostr
[i
]
398 return joinfields(L
, "")
400 # Substring replacement (global)
401 def replace(s
, old
, new
, maxsplit
=0):
402 """replace (str, old, new[, maxsplit]) -> string
404 Return a copy of string str with all occurrences of substring
405 old replaced by new. If the optional argument maxsplit is
406 given, only the first maxsplit occurrences are replaced.
409 return s
.replace(old
, new
, maxsplit
)
414 # If string objects do not have methods, then we need to use the old string.py
415 # library, which uses strop for many more things than just the few outlined
419 except AttributeError:
420 from stringold
import *
422 # Try importing optional built-in module "strop" -- if it exists,
423 # it redefines some string operations that are 100-1000 times faster.
424 # It also defines values for whitespace, lowercase and uppercase
425 # that match <ctype.h>'s definitions.
428 from strop
import maketrans
, lowercase
, uppercase
, whitespace
429 letters
= lowercase
+ uppercase
431 pass # Use the original versions