1 """A collection of string operations (most are no longer used in Python 1.6).
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 Public module variables:
10 whitespace -- a string containing all characters considered whitespace
11 lowercase -- a string containing all characters considered lowercase letters
12 uppercase -- a string containing all characters considered uppercase letters
13 letters -- a string containing all characters considered letters
14 digits -- a string containing all characters considered decimal digits
15 hexdigits -- a string containing all characters considered hexadecimal digits
16 octdigits -- a string containing all characters considered octal digits
20 # Some strings for ctype-style character classification
21 whitespace
= ' \t\n\r\v\f'
22 lowercase
= 'abcdefghijklmnopqrstuvwxyz'
23 uppercase
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
24 letters
= lowercase
+ uppercase
26 hexdigits
= digits
+ 'abcdef' + 'ABCDEF'
27 octdigits
= '01234567'
29 # Case conversion helpers
31 for i
in range(256): _idmap
= _idmap
+ chr(i
)
34 # Backward compatible names for exceptions
35 index_error
= ValueError
36 atoi_error
= ValueError
37 atof_error
= ValueError
38 atol_error
= ValueError
40 # convert UPPER CASE letters to lower case
44 Return a copy of the string s converted to lowercase.
49 # Convert lower case letters to UPPER CASE
53 Return a copy of the string s converted to uppercase.
58 # Swap lower case letters and UPPER CASE
60 """swapcase(s) -> string
62 Return a copy of the string s with upper case characters
63 converted to lowercase and vice versa.
68 # Strip leading and trailing tabs and spaces
72 Return a copy of the string s with leading and trailing
78 # Strip leading tabs and spaces
80 """lstrip(s) -> string
82 Return a copy of the string s with leading whitespace removed.
87 # Strip trailing tabs and spaces
89 """rstrip(s) -> string
91 Return a copy of the string s with trailing whitespace
98 # Split a string into a list of space/tab-separated words
99 # NB: split(s) is NOT the same as splitfields(s, ' ')!
100 def split(s
, sep
=None, maxsplit
=-1):
101 """split(s [,sep [,maxsplit]]) -> list of strings
103 Return a list of the words in the string s, using sep as the
104 delimiter string. If maxsplit is given, splits into at most
105 maxsplit words. If sep is not specified, any whitespace string
108 (split and splitfields are synonymous)
111 return s
.split(sep
, maxsplit
)
114 # Join fields with optional separator
115 def join(words
, sep
= ' '):
116 """join(list [,sep]) -> string
118 Return a string composed of the words in list, with
119 intervening occurences of sep. The default separator is a
122 (joinfields and join are synonymous)
125 return sep
.join(words
)
128 # for a little bit of speed
131 # Find substring, raise exception if not found
133 """index(s, sub [,start [,end]]) -> int
135 Like find but raises ValueError when the substring is not found.
138 return _apply(s
.index
, args
)
140 # Find last substring, raise exception if not found
141 def rindex(s
, *args
):
142 """rindex(s, sub [,start [,end]]) -> int
144 Like rfind but raises ValueError when the substring is not found.
147 return _apply(s
.rindex
, args
)
149 # Count non-overlapping occurrences of substring
151 """count(s, sub[, start[,end]]) -> int
153 Return the number of occurrences of substring sub in string
154 s[start:end]. Optional arguments start and end are
155 interpreted as in slice notation.
158 return _apply(s
.count
, args
)
160 # Find substring, return -1 if not found
162 """find(s, sub [,start [,end]]) -> in
164 Return the lowest index in s where substring sub is found,
165 such that sub is contained within s[start,end]. Optional
166 arguments start and end are interpreted as in slice notation.
168 Return -1 on failure.
171 return _apply(s
.find
, args
)
173 # Find last substring, return -1 if not found
175 """rfind(s, sub [,start [,end]]) -> int
177 Return the highest index in s where substring sub is found,
178 such that sub is contained within s[start,end]. Optional
179 arguments start and end are interpreted as in slice notation.
181 Return -1 on failure.
184 return _apply(s
.rfind
, args
)
190 _StringType
= type('')
192 # Convert string to float
196 Return the floating point number represented by the string s.
199 if type(s
) == _StringType
:
202 raise TypeError('argument 1: expected string, %s found' %
205 # Convert string to integer
207 """atoi(s [,base]) -> int
209 Return the integer represented by the string s in the given
210 base, which defaults to 10. The string s must consist of one
211 or more digits, possibly preceded by a sign. If base is 0, it
212 is chosen from the leading characters of s, 0 for octal, 0x or
213 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
220 raise TypeError('function requires at least 1 argument: %d given' %
222 # Don't catch type error resulting from too many arguments to int(). The
223 # error message isn't compatible but the error type is, and this function
224 # is complicated enough already.
225 if type(s
) == _StringType
:
226 return _apply(_int
, args
)
228 raise TypeError('argument 1: expected string, %s found' %
232 # Convert string to long integer
234 """atol(s [,base]) -> long
236 Return the long integer represented by the string s in the
237 given base, which defaults to 10. The string s must consist
238 of one or more digits, possibly preceded by a sign. If base
239 is 0, it is chosen from the leading characters of s, 0 for
240 octal, 0x or 0X for hexadecimal. If base is 16, a preceding
241 0x or 0X is accepted. A trailing L or l is not accepted,
248 raise TypeError('function requires at least 1 argument: %d given' %
250 # Don't catch type error resulting from too many arguments to long(). The
251 # error message isn't compatible but the error type is, and this function
252 # is complicated enough already.
253 if type(s
) == _StringType
:
254 return _apply(_long
, args
)
256 raise TypeError('argument 1: expected string, %s found' %
260 # Left-justify a string
262 """ljust(s, width) -> string
264 Return a left-justified version of s, in a field of the
265 specified width, padded with spaces as needed. The string is
273 # Right-justify a string
275 """rjust(s, width) -> string
277 Return a right-justified version of s, in a field of the
278 specified width, padded with spaces as needed. The string is
287 def center(s
, width
):
288 """center(s, width) -> string
290 Return a center version of s, in a field of the specified
291 width. padded with spaces as needed. The string is never
299 # This ensures that center(center(s, i), j) = center(s, j)
301 return ' '*half
+ s
+ ' '*(n
-half
)
303 # Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
304 # Decadent feature: the argument may be a string or a number
305 # (Use of this is deprecated; it should be a string as with ljust c.s.)
307 """zfill(x, width) -> string
309 Pad a numeric string x with zeros on the left, to fill a field
310 of the specified width. The string x is never truncated.
313 if type(x
) == type(''): s
= x
316 if n
>= width
: return s
318 if s
[0] in ('-', '+'):
319 sign
, s
= s
[0], s
[1:]
320 return sign
+ '0'*(width
-n
) + s
322 # Expand tabs in a string.
323 # Doesn't take non-printing chars into account, but does understand \n.
324 def expandtabs(s
, tabsize
=8):
325 """expandtabs(s [,tabsize]) -> string
327 Return a copy of the string s with all tab characters replaced
328 by the appropriate number of spaces, depending on the current
329 column, and the tabsize (default 8).
335 c
= ' '*(tabsize
- len(line
) % tabsize
)
342 # Character translation through look-up table.
343 def translate(s
, table
, deletions
=""):
344 """translate(s,table [,deletechars]) -> string
346 Return a copy of the string s, where all characters occurring
347 in the optional argument deletechars are removed, and the
348 remaining characters have been mapped through the given
349 translation table, which must be a string of length 256.
352 return s
.translate(table
, deletions
)
354 # Capitalize a string, e.g. "aBc dEf" -> "Abc def".
356 """capitalize(s) -> string
358 Return a copy of the string s with only its first character
362 return s
.capitalize()
364 # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
365 # See also regsub.capwords().
366 def capwords(s
, sep
=None):
367 """capwords(s, [sep]) -> string
369 Split the argument into words using split, capitalize each
370 word using capitalize, and join the capitalized words using
371 join. Note that this replaces runs of whitespace characters by
375 return join(map(capitalize
, s
.split(sep
)), sep
or ' ')
377 # Construct a translation string
379 def maketrans(fromstr
, tostr
):
380 """maketrans(frm, to) -> string
382 Return a translation table (a string of 256 bytes long)
383 suitable for use in string.translate. The strings frm and to
384 must be of the same length.
387 if len(fromstr
) != len(tostr
):
388 raise ValueError, "maketrans arguments must have same length"
391 _idmapL
= map(None, _idmap
)
393 fromstr
= map(ord, fromstr
)
394 for i
in range(len(fromstr
)):
395 L
[fromstr
[i
]] = tostr
[i
]
396 return joinfields(L
, "")
398 # Substring replacement (global)
399 def replace(s
, old
, new
, maxsplit
=-1):
400 """replace (str, old, new[, maxsplit]) -> string
402 Return a copy of string str with all occurrences of substring
403 old replaced by new. If the optional argument maxsplit is
404 given, only the first maxsplit occurrences are replaced.
407 return s
.replace(old
, new
, maxsplit
)
412 # If string objects do not have methods, then we need to use the old string.py
413 # library, which uses strop for many more things than just the few outlined
417 except AttributeError:
418 from stringold
import *
420 # Try importing optional built-in module "strop" -- if it exists,
421 # it redefines some string operations that are 100-1000 times faster.
422 # It also defines values for whitespace, lowercase and uppercase
423 # that match <ctype.h>'s definitions.
426 from strop
import maketrans
, lowercase
, uppercase
, whitespace
427 letters
= lowercase
+ uppercase
429 pass # Use the original versions