blob: 764c396bb07a3bab70eb26cfa09c1dbecdaa37d9 [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# module 'string' -- A collection of string operations
2
Guido van Rossume7113b61993-03-29 11:30:50 +00003# Warning: most of the code you see here isn't normally used nowadays.
4# At the end of this file most functions are replaced by built-in
5# functions imported from built-in module "strop".
Guido van Rossumc6360141990-10-13 19:23:40 +00006
7# Some strings for ctype-style character classification
Guido van Rossum8e2ec561993-07-29 09:37:38 +00008whitespace = ' \t\n\r\v\f'
Guido van Rossumc6360141990-10-13 19:23:40 +00009lowercase = 'abcdefghijklmnopqrstuvwxyz'
10uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
11letters = lowercase + uppercase
12digits = '0123456789'
13hexdigits = digits + 'abcdef' + 'ABCDEF'
14octdigits = '01234567'
15
16# Case conversion helpers
Guido van Rossuma61ff7b1992-01-14 18:31:29 +000017_idmap = ''
18for i in range(256): _idmap = _idmap + chr(i)
19_lower = _idmap[:ord('A')] + lowercase + _idmap[ord('Z')+1:]
20_upper = _idmap[:ord('a')] + uppercase + _idmap[ord('z')+1:]
21_swapcase = _upper[:ord('A')] + lowercase + _upper[ord('Z')+1:]
Guido van Rossumc6360141990-10-13 19:23:40 +000022del i
23
24# convert UPPER CASE letters to lower case
25def lower(s):
26 res = ''
27 for c in s:
Guido van Rossuma61ff7b1992-01-14 18:31:29 +000028 res = res + _lower[ord(c)]
Guido van Rossumc6360141990-10-13 19:23:40 +000029 return res
30
31# Convert lower case letters to UPPER CASE
32def upper(s):
33 res = ''
34 for c in s:
Guido van Rossuma61ff7b1992-01-14 18:31:29 +000035 res = res + _upper[ord(c)]
Guido van Rossumc6360141990-10-13 19:23:40 +000036 return res
37
38# Swap lower case letters and UPPER CASE
39def swapcase(s):
40 res = ''
41 for c in s:
Guido van Rossuma61ff7b1992-01-14 18:31:29 +000042 res = res + _swapcase[ord(c)]
Guido van Rossumc6360141990-10-13 19:23:40 +000043 return res
44
45# Strip leading and trailing tabs and spaces
46def strip(s):
47 i, j = 0, len(s)
48 while i < j and s[i] in whitespace: i = i+1
49 while i < j and s[j-1] in whitespace: j = j-1
50 return s[i:j]
51
52# Split a string into a list of space/tab-separated words
53# NB: split(s) is NOT the same as splitfields(s, ' ')!
54def split(s):
55 res = []
56 i, n = 0, len(s)
57 while i < n:
58 while i < n and s[i] in whitespace: i = i+1
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000059 if i == n: break
Guido van Rossumc6360141990-10-13 19:23:40 +000060 j = i
61 while j < n and s[j] not in whitespace: j = j+1
62 res.append(s[i:j])
63 i = j
64 return res
65
66# Split a list into fields separated by a given string
67# NB: splitfields(s, ' ') is NOT the same as split(s)!
Guido van Rossum7a461e51992-09-20 21:41:09 +000068# splitfields(s, '') returns [s] (in analogy with split() in nawk)
Guido van Rossumc6360141990-10-13 19:23:40 +000069def splitfields(s, sep):
70 res = []
Guido van Rossumc6360141990-10-13 19:23:40 +000071 nsep = len(sep)
Guido van Rossumae507a41992-08-19 16:49:58 +000072 if nsep == 0:
Guido van Rossum7a461e51992-09-20 21:41:09 +000073 return [s]
Guido van Rossumae507a41992-08-19 16:49:58 +000074 ns = len(s)
Guido van Rossumc6360141990-10-13 19:23:40 +000075 i = j = 0
76 while j+nsep <= ns:
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000077 if s[j:j+nsep] == sep:
Guido van Rossumc6360141990-10-13 19:23:40 +000078 res.append(s[i:j])
79 i = j = j + nsep
80 else:
81 j = j + 1
82 res.append(s[i:])
83 return res
84
Guido van Rossumfac38b71991-04-07 13:42:19 +000085# Join words with spaces between them
86def join(words):
Guido van Rossum18fc5691992-11-26 09:17:19 +000087 return joinfields(words, ' ')
Guido van Rossumfac38b71991-04-07 13:42:19 +000088
89# Join fields with separator
90def joinfields(words, sep):
91 res = ''
92 for w in words:
93 res = res + (sep + w)
94 return res[len(sep):]
95
Guido van Rossumd3166071993-05-24 14:16:22 +000096# Find substring, raise exception if not found
Guido van Rossumc6360141990-10-13 19:23:40 +000097index_error = 'substring not found in string.index'
Guido van Rossumc629d341992-11-05 10:43:02 +000098def index(s, sub, *args):
99 if args:
100 if len(args) > 1:
101 raise TypeError, 'string.index(): too many args'
102 i = args[0]
103 else:
104 i = 0
Guido van Rossumc6360141990-10-13 19:23:40 +0000105 n = len(sub)
Guido van Rossumc629d341992-11-05 10:43:02 +0000106 m = len(s) + 1 - n
107 while i < m:
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000108 if sub == s[i:i+n]: return i
Guido van Rossumc629d341992-11-05 10:43:02 +0000109 i = i+1
Guido van Rossumd3166071993-05-24 14:16:22 +0000110 raise index_error, (s, sub) + args
111
112# Find substring, return -1 if not found
113def find(*args):
114 try:
115 return apply(index, args)
116 except index_error:
117 return -1
Guido van Rossumc6360141990-10-13 19:23:40 +0000118
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000119# Convert string to float
120atof_error = 'non-float argument to string.atof'
121def atof(str):
122 import regex
123 sign = ''
124 s = str
125 if s and s[0] in '+-':
126 sign = s[0]
127 s = s[1:]
128 if not s: raise atof_error, str
129 while s[0] == '0' and len(s) > 1 and s[1] in digits: s = s[1:]
130 if regex.match('[0-9]*\(\.[0-9]*\)?\([eE][-+]?[0-9]+\)?', s) != len(s):
131 raise atof_error, str
132 try:
133 return eval(sign + s)
134 except SyntaxError:
135 raise atof_error, str
136
Guido van Rossumc6360141990-10-13 19:23:40 +0000137# Convert string to integer
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000138atoi_error = 'non-integer argument to string.atoi'
Guido van Rossumc6360141990-10-13 19:23:40 +0000139def atoi(str):
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000140 sign = ''
Guido van Rossumc6360141990-10-13 19:23:40 +0000141 s = str
Guido van Rossumc629d341992-11-05 10:43:02 +0000142 if s and s[0] in '+-':
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000143 sign = s[0]
144 s = s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000145 if not s: raise atoi_error, str
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000146 while s[0] == '0' and len(s) > 1: s = s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000147 for c in s:
148 if c not in digits: raise atoi_error, str
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000149 return eval(sign + s)
Guido van Rossumc6360141990-10-13 19:23:40 +0000150
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000151# Convert string to long integer
152atol_error = 'non-integer argument to string.atol'
153def atol(str):
154 sign = ''
155 s = str
156 if s and s[0] in '+-':
157 sign = s[0]
158 s = s[1:]
159 if not s: raise atoi_error, str
160 while s[0] == '0' and len(s) > 1: s = s[1:]
161 for c in s:
162 if c not in digits: raise atoi_error, str
163 return eval(sign + s + 'L')
164
Guido van Rossumc6360141990-10-13 19:23:40 +0000165# Left-justify a string
166def ljust(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000167 n = width - len(s)
168 if n <= 0: return s
169 return s + ' '*n
Guido van Rossumc6360141990-10-13 19:23:40 +0000170
171# Right-justify a string
172def rjust(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000173 n = width - len(s)
174 if n <= 0: return s
175 return ' '*n + s
Guido van Rossumc6360141990-10-13 19:23:40 +0000176
177# Center a string
178def center(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000179 n = width - len(s)
180 if n <= 0: return s
181 half = n/2
182 if n%2 and width%2:
183 # This ensures that center(center(s, i), j) = center(s, j)
184 half = half+1
185 return ' '*half + s + ' '*(n-half)
Guido van Rossumc6360141990-10-13 19:23:40 +0000186
187# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
188# Decadent feature: the argument may be a string or a number
189# (Use of this is deprecated; it should be a string as with ljust c.s.)
190def zfill(x, width):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000191 if type(x) == type(''): s = x
Guido van Rossumc6360141990-10-13 19:23:40 +0000192 else: s = `x`
193 n = len(s)
194 if n >= width: return s
195 sign = ''
Guido van Rossum333c2e01991-08-16 13:29:03 +0000196 if s[0] in ('-', '+'):
197 sign, s = s[0], s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000198 return sign + '0'*(width-n) + s
Guido van Rossum6ff2e901992-03-27 15:13:31 +0000199
200# Expand tabs in a string.
201# Doesn't take non-printing chars into account, but does understand \n.
202def expandtabs(s, tabsize):
203 res = line = ''
204 for c in s:
205 if c == '\t':
206 c = ' '*(tabsize - len(line)%tabsize)
207 line = line + c
208 if c == '\n':
209 res = res + line
210 line = ''
211 return res + line
Guido van Rossum2db91351992-10-18 17:09:59 +0000212
213
214# Try importing optional built-in module "strop" -- if it exists,
215# it redefines some string operations that are 100-1000 times faster.
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000216# It also defines values for whitespace, lowercase and uppercase
217# that match <ctype.h>'s definitions.
Guido van Rossum2db91351992-10-18 17:09:59 +0000218# The manipulation with index_error is needed for compatibility.
219
220try:
221 from strop import *
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000222 letters = lowercase + uppercase
Guido van Rossum2db91351992-10-18 17:09:59 +0000223 from strop import index
224 index_error = ValueError
225except ImportError:
226 pass # Use the original, slow versions