ยปCore Development>Code coverage>Lib/stringold.py

Python code coverage for Lib/stringold.py

#countcontent
1n/a# module 'string' -- A collection of string operations
2n/a
3n/a# Warning: most of the code you see here isn't normally used nowadays. With
4n/a# Python 1.6, many of these functions are implemented as methods on the
5n/a# standard string object. They used to be implemented by a built-in module
6n/a# called strop, but strop is now obsolete itself.
7n/a
8n/a"""Common string manipulations.
9n/a
10n/aPublic module variables:
11n/a
12n/awhitespace -- a string containing all characters considered whitespace
13n/alowercase -- a string containing all characters considered lowercase letters
14n/auppercase -- a string containing all characters considered uppercase letters
15n/aletters -- a string containing all characters considered letters
16n/adigits -- a string containing all characters considered decimal digits
17n/ahexdigits -- a string containing all characters considered hexadecimal digits
18n/aoctdigits -- a string containing all characters considered octal digits
19n/a
201"""
211from warnings import warnpy3k
221warnpy3k("the stringold module has been removed in Python 3.0", stacklevel=2)
231del warnpy3k
24n/a
25n/a# Some strings for ctype-style character classification
261whitespace = ' \t\n\r\v\f'
271lowercase = 'abcdefghijklmnopqrstuvwxyz'
281uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
291letters = lowercase + uppercase
301digits = '0123456789'
311hexdigits = digits + 'abcdef' + 'ABCDEF'
321octdigits = '01234567'
33n/a
34n/a# Case conversion helpers
351_idmap = ''
36257for i in range(256): _idmap = _idmap + chr(i)
371del i
38n/a
39n/a# Backward compatible names for exceptions
401index_error = ValueError
411atoi_error = ValueError
421atof_error = ValueError
431atol_error = ValueError
44n/a
45n/a# convert UPPER CASE letters to lower case
461def lower(s):
47n/a """lower(s) -> string
48n/a
49n/a Return a copy of the string s converted to lowercase.
50n/a
51n/a """
520 return s.lower()
53n/a
54n/a# Convert lower case letters to UPPER CASE
551def upper(s):
56n/a """upper(s) -> string
57n/a
58n/a Return a copy of the string s converted to uppercase.
59n/a
60n/a """
610 return s.upper()
62n/a
63n/a# Swap lower case letters and UPPER CASE
641def swapcase(s):
65n/a """swapcase(s) -> string
66n/a
67n/a Return a copy of the string s with upper case characters
68n/a converted to lowercase and vice versa.
69n/a
70n/a """
710 return s.swapcase()
72n/a
73n/a# Strip leading and trailing tabs and spaces
741def strip(s):
75n/a """strip(s) -> string
76n/a
77n/a Return a copy of the string s with leading and trailing
78n/a whitespace removed.
79n/a
80n/a """
810 return s.strip()
82n/a
83n/a# Strip leading tabs and spaces
841def lstrip(s):
85n/a """lstrip(s) -> string
86n/a
87n/a Return a copy of the string s with leading whitespace removed.
88n/a
89n/a """
900 return s.lstrip()
91n/a
92n/a# Strip trailing tabs and spaces
931def rstrip(s):
94n/a """rstrip(s) -> string
95n/a
96n/a Return a copy of the string s with trailing whitespace
97n/a removed.
98n/a
99n/a """
1000 return s.rstrip()
101n/a
102n/a
103n/a# Split a string into a list of space/tab-separated words
1041def split(s, sep=None, maxsplit=0):
105n/a """split(str [,sep [,maxsplit]]) -> list of strings
106n/a
107n/a Return a list of the words in the string s, using sep as the
108n/a delimiter string. If maxsplit is nonzero, splits into at most
109n/a maxsplit words If sep is not specified, any whitespace string
110n/a is a separator. Maxsplit defaults to 0.
111n/a
112n/a (split and splitfields are synonymous)
113n/a
114n/a """
1150 return s.split(sep, maxsplit)
1161splitfields = split
117n/a
118n/a# Join fields with optional separator
1191def join(words, sep = ' '):
120n/a """join(list [,sep]) -> string
121n/a
122n/a Return a string composed of the words in list, with
123n/a intervening occurrences of sep. The default separator is a
124n/a single space.
125n/a
126n/a (joinfields and join are synonymous)
127n/a
128n/a """
1290 return sep.join(words)
1301joinfields = join
131n/a
132n/a# for a little bit of speed
1331_apply = apply
134n/a
135n/a# Find substring, raise exception if not found
1361def index(s, *args):
137n/a """index(s, sub [,start [,end]]) -> int
138n/a
139n/a Like find but raises ValueError when the substring is not found.
140n/a
141n/a """
1420 return _apply(s.index, args)
143n/a
144n/a# Find last substring, raise exception if not found
1451def rindex(s, *args):
146n/a """rindex(s, sub [,start [,end]]) -> int
147n/a
148n/a Like rfind but raises ValueError when the substring is not found.
149n/a
150n/a """
1510 return _apply(s.rindex, args)
152n/a
153n/a# Count non-overlapping occurrences of substring
1541def count(s, *args):
155n/a """count(s, sub[, start[,end]]) -> int
156n/a
157n/a Return the number of occurrences of substring sub in string
158n/a s[start:end]. Optional arguments start and end are
159n/a interpreted as in slice notation.
160n/a
161n/a """
1620 return _apply(s.count, args)
163n/a
164n/a# Find substring, return -1 if not found
1651def find(s, *args):
166n/a """find(s, sub [,start [,end]]) -> in
167n/a
168n/a Return the lowest index in s where substring sub is found,
169n/a such that sub is contained within s[start,end]. Optional
170n/a arguments start and end are interpreted as in slice notation.
171n/a
172n/a Return -1 on failure.
173n/a
174n/a """
1750 return _apply(s.find, args)
176n/a
177n/a# Find last substring, return -1 if not found
1781def rfind(s, *args):
179n/a """rfind(s, sub [,start [,end]]) -> int
180n/a
181n/a Return the highest index in s where substring sub is found,
182n/a such that sub is contained within s[start,end]. Optional
183n/a arguments start and end are interpreted as in slice notation.
184n/a
185n/a Return -1 on failure.
186n/a
187n/a """
1880 return _apply(s.rfind, args)
189n/a
190n/a# for a bit of speed
1911_float = float
1921_int = int
1931_long = long
1941_StringType = type('')
195n/a
196n/a# Convert string to float
1971def atof(s):
198n/a """atof(s) -> float
199n/a
200n/a Return the floating point number represented by the string s.
201n/a
202n/a """
2030 if type(s) == _StringType:
2040 return _float(s)
205n/a else:
2060 raise TypeError('argument 1: expected string, %s found' %
2070 type(s).__name__)
208n/a
209n/a# Convert string to integer
2101def atoi(*args):
211n/a """atoi(s [,base]) -> int
212n/a
213n/a Return the integer represented by the string s in the given
214n/a base, which defaults to 10. The string s must consist of one
215n/a or more digits, possibly preceded by a sign. If base is 0, it
216n/a is chosen from the leading characters of s, 0 for octal, 0x or
217n/a 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
218n/a accepted.
219n/a
220n/a """
2210 try:
2220 s = args[0]
2230 except IndexError:
2240 raise TypeError('function requires at least 1 argument: %d given' %
2250 len(args))
226n/a # Don't catch type error resulting from too many arguments to int(). The
227n/a # error message isn't compatible but the error type is, and this function
228n/a # is complicated enough already.
2290 if type(s) == _StringType:
2300 return _apply(_int, args)
231n/a else:
2320 raise TypeError('argument 1: expected string, %s found' %
2330 type(s).__name__)
234n/a
235n/a
236n/a# Convert string to long integer
2371def atol(*args):
238n/a """atol(s [,base]) -> long
239n/a
240n/a Return the long integer represented by the string s in the
241n/a given base, which defaults to 10. The string s must consist
242n/a of one or more digits, possibly preceded by a sign. If base
243n/a is 0, it is chosen from the leading characters of s, 0 for
244n/a octal, 0x or 0X for hexadecimal. If base is 16, a preceding
245n/a 0x or 0X is accepted. A trailing L or l is not accepted,
246n/a unless base is 0.
247n/a
248n/a """
2490 try:
2500 s = args[0]
2510 except IndexError:
2520 raise TypeError('function requires at least 1 argument: %d given' %
2530 len(args))
254n/a # Don't catch type error resulting from too many arguments to long(). The
255n/a # error message isn't compatible but the error type is, and this function
256n/a # is complicated enough already.
2570 if type(s) == _StringType:
2580 return _apply(_long, args)
259n/a else:
2600 raise TypeError('argument 1: expected string, %s found' %
2610 type(s).__name__)
262n/a
263n/a
264n/a# Left-justify a string
2651def ljust(s, width):
266n/a """ljust(s, width) -> string
267n/a
268n/a Return a left-justified version of s, in a field of the
269n/a specified width, padded with spaces as needed. The string is
270n/a never truncated.
271n/a
272n/a """
2730 n = width - len(s)
2740 if n <= 0: return s
2750 return s + ' '*n
276n/a
277n/a# Right-justify a string
2781def rjust(s, width):
279n/a """rjust(s, width) -> string
280n/a
281n/a Return a right-justified version of s, in a field of the
282n/a specified width, padded with spaces as needed. The string is
283n/a never truncated.
284n/a
285n/a """
2860 n = width - len(s)
2870 if n <= 0: return s
2880 return ' '*n + s
289n/a
290n/a# Center a string
2911def center(s, width):
292n/a """center(s, width) -> string
293n/a
294n/a Return a center version of s, in a field of the specified
295n/a width. padded with spaces as needed. The string is never
296n/a truncated.
297n/a
298n/a """
2990 n = width - len(s)
3000 if n <= 0: return s
3010 half = n/2
3020 if n%2 and width%2:
303n/a # This ensures that center(center(s, i), j) = center(s, j)
3040 half = half+1
3050 return ' '*half + s + ' '*(n-half)
306n/a
307n/a# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
308n/a# Decadent feature: the argument may be a string or a number
309n/a# (Use of this is deprecated; it should be a string as with ljust c.s.)
3101def zfill(x, width):
311n/a """zfill(x, width) -> string
312n/a
313n/a Pad a numeric string x with zeros on the left, to fill a field
314n/a of the specified width. The string x is never truncated.
315n/a
316n/a """
3170 if type(x) == type(''): s = x
3180 else: s = repr(x)
3190 n = len(s)
3200 if n >= width: return s
3210 sign = ''
3220 if s[0] in ('-', '+'):
3230 sign, s = s[0], s[1:]
3240 return sign + '0'*(width-n) + s
325n/a
326n/a# Expand tabs in a string.
327n/a# Doesn't take non-printing chars into account, but does understand \n.
3281def expandtabs(s, tabsize=8):
329n/a """expandtabs(s [,tabsize]) -> string
330n/a
331n/a Return a copy of the string s with all tab characters replaced
332n/a by the appropriate number of spaces, depending on the current
333n/a column, and the tabsize (default 8).
334n/a
335n/a """
3360 res = line = ''
3370 for c in s:
3380 if c == '\t':
3390 c = ' '*(tabsize - len(line) % tabsize)
3400 line = line + c
3410 if c == '\n':
3420 res = res + line
3430 line = ''
3440 return res + line
345n/a
346n/a# Character translation through look-up table.
3471def translate(s, table, deletions=""):
348n/a """translate(s,table [,deletechars]) -> string
349n/a
350n/a Return a copy of the string s, where all characters occurring
351n/a in the optional argument deletechars are removed, and the
352n/a remaining characters have been mapped through the given
353n/a translation table, which must be a string of length 256.
354n/a
355n/a """
3560 return s.translate(table, deletions)
357n/a
358n/a# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
3591def capitalize(s):
360n/a """capitalize(s) -> string
361n/a
362n/a Return a copy of the string s with only its first character
363n/a capitalized.
364n/a
365n/a """
3660 return s.capitalize()
367n/a
368n/a# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
3691def capwords(s, sep=None):
370n/a """capwords(s, [sep]) -> string
371n/a
372n/a Split the argument into words using split, capitalize each
373n/a word using capitalize, and join the capitalized words using
374n/a join. Note that this replaces runs of whitespace characters by
375n/a a single space.
376n/a
377n/a """
3780 return join(map(capitalize, s.split(sep)), sep or ' ')
379n/a
380n/a# Construct a translation string
3811_idmapL = None
3821def maketrans(fromstr, tostr):
383n/a """maketrans(frm, to) -> string
384n/a
385n/a Return a translation table (a string of 256 bytes long)
386n/a suitable for use in string.translate. The strings frm and to
387n/a must be of the same length.
388n/a
389n/a """
3900 if len(fromstr) != len(tostr):
3910 raise ValueError, "maketrans arguments must have same length"
392n/a global _idmapL
3930 if not _idmapL:
3940 _idmapL = list(_idmap)
3950 L = _idmapL[:]
3960 fromstr = map(ord, fromstr)
3970 for i in range(len(fromstr)):
3980 L[fromstr[i]] = tostr[i]
3990 return join(L, "")
400n/a
401n/a# Substring replacement (global)
4021def replace(s, old, new, maxsplit=0):
403n/a """replace (str, old, new[, maxsplit]) -> string
404n/a
405n/a Return a copy of string str with all occurrences of substring
406n/a old replaced by new. If the optional argument maxsplit is
407n/a given, only the first maxsplit occurrences are replaced.
408n/a
409n/a """
4100 return s.replace(old, new, maxsplit)
411n/a
412n/a
413n/a# XXX: transitional
414n/a#
415n/a# If string objects do not have methods, then we need to use the old string.py
416n/a# library, which uses strop for many more things than just the few outlined
417n/a# below.
4181try:
4191 ''.upper
4200except AttributeError:
4210 from stringold import *
422n/a
423n/a# Try importing optional built-in module "strop" -- if it exists,
424n/a# it redefines some string operations that are 100-1000 times faster.
425n/a# It also defines values for whitespace, lowercase and uppercase
426n/a# that match <ctype.h>'s definitions.
427n/a
4281try:
4291 from strop import maketrans, lowercase, uppercase, whitespace
4301 letters = lowercase + uppercase
4310except ImportError:
4320 pass # Use the original versions