blob: a37cbf006160ed43018eba312bb13605d764aa40 [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 Rossumb6775db1994-08-01 11:34:53 +000098def index(s, sub, i = 0):
99 if i < 0: i = i + len(s)
Guido van Rossumc6360141990-10-13 19:23:40 +0000100 n = len(sub)
Guido van Rossumc629d341992-11-05 10:43:02 +0000101 m = len(s) + 1 - n
102 while i < m:
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000103 if sub == s[i:i+n]: return i
Guido van Rossumc629d341992-11-05 10:43:02 +0000104 i = i+1
Guido van Rossumb6775db1994-08-01 11:34:53 +0000105 raise index_error, (s, sub, i)
Guido van Rossumd3166071993-05-24 14:16:22 +0000106
Guido van Rossume65cce51993-11-08 15:05:21 +0000107# Find last substring, raise exception if not found
Guido van Rossumb6775db1994-08-01 11:34:53 +0000108def rindex(s, sub, i = 0):
109 if i < 0: i = i + len(s)
Guido van Rossume65cce51993-11-08 15:05:21 +0000110 n = len(sub)
111 m = len(s) + 1 - n
112 r = None
113 while i < m:
114 if sub == s[i:i+n]: r = i
115 i = i+1
116 if r is None:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000117 raise index_error, (s, sub, i)
118 return r
119
120# Count non-overlapping occurrences of substring
121def count(s, sub, i = 0):
122 if i < 0: i = i + len(s)
123 n = len(sub)
124 m = len(s) + 1 - n
125 if n == 0: return m-i
126 r = 0
127 while i < m:
128 if sub == s[i:i+n]:
129 r = r+1
130 i = i+n
131 else:
132 i = i+1
Guido van Rossume65cce51993-11-08 15:05:21 +0000133 return r
134
Guido van Rossumd3166071993-05-24 14:16:22 +0000135# Find substring, return -1 if not found
Guido van Rossumb6775db1994-08-01 11:34:53 +0000136def find(s, sub, i = 0):
Guido van Rossumd3166071993-05-24 14:16:22 +0000137 try:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000138 return index(s, sub, i)
Guido van Rossumd3166071993-05-24 14:16:22 +0000139 except index_error:
140 return -1
Guido van Rossumc6360141990-10-13 19:23:40 +0000141
Guido van Rossume65cce51993-11-08 15:05:21 +0000142# Find last substring, return -1 if not found
Guido van Rossumb6775db1994-08-01 11:34:53 +0000143def rfind(s, sub, i = 0):
Guido van Rossume65cce51993-11-08 15:05:21 +0000144 try:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000145 return rindex(s, sub, i)
Guido van Rossume65cce51993-11-08 15:05:21 +0000146 except index_error:
147 return -1
148
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000149# Convert string to float
150atof_error = 'non-float argument to string.atof'
151def atof(str):
152 import regex
153 sign = ''
154 s = str
155 if s and s[0] in '+-':
156 sign = s[0]
157 s = s[1:]
158 if not s: raise atof_error, str
159 while s[0] == '0' and len(s) > 1 and s[1] in digits: s = s[1:]
160 if regex.match('[0-9]*\(\.[0-9]*\)?\([eE][-+]?[0-9]+\)?', s) != len(s):
161 raise atof_error, str
162 try:
Guido van Rossumb6775db1994-08-01 11:34:53 +0000163 return float(eval(sign + s))
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000164 except SyntaxError:
165 raise atof_error, str
166
Guido van Rossumc6360141990-10-13 19:23:40 +0000167# Convert string to integer
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000168atoi_error = 'non-integer argument to string.atoi'
Guido van Rossumc6360141990-10-13 19:23:40 +0000169def atoi(str):
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000170 sign = ''
Guido van Rossumc6360141990-10-13 19:23:40 +0000171 s = str
Guido van Rossumc629d341992-11-05 10:43:02 +0000172 if s and s[0] in '+-':
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000173 sign = s[0]
174 s = s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000175 if not s: raise atoi_error, str
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000176 while s[0] == '0' and len(s) > 1: s = s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000177 for c in s:
178 if c not in digits: raise atoi_error, str
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000179 return eval(sign + s)
Guido van Rossumc6360141990-10-13 19:23:40 +0000180
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000181# Convert string to long integer
182atol_error = 'non-integer argument to string.atol'
183def atol(str):
184 sign = ''
185 s = str
186 if s and s[0] in '+-':
187 sign = s[0]
188 s = s[1:]
189 if not s: raise atoi_error, str
190 while s[0] == '0' and len(s) > 1: s = s[1:]
191 for c in s:
192 if c not in digits: raise atoi_error, str
193 return eval(sign + s + 'L')
194
Guido van Rossumc6360141990-10-13 19:23:40 +0000195# Left-justify a string
196def ljust(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000197 n = width - len(s)
198 if n <= 0: return s
199 return s + ' '*n
Guido van Rossumc6360141990-10-13 19:23:40 +0000200
201# Right-justify a string
202def rjust(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000203 n = width - len(s)
204 if n <= 0: return s
205 return ' '*n + s
Guido van Rossumc6360141990-10-13 19:23:40 +0000206
207# Center a string
208def center(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000209 n = width - len(s)
210 if n <= 0: return s
211 half = n/2
212 if n%2 and width%2:
213 # This ensures that center(center(s, i), j) = center(s, j)
214 half = half+1
215 return ' '*half + s + ' '*(n-half)
Guido van Rossumc6360141990-10-13 19:23:40 +0000216
217# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
218# Decadent feature: the argument may be a string or a number
219# (Use of this is deprecated; it should be a string as with ljust c.s.)
220def zfill(x, width):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000221 if type(x) == type(''): s = x
Guido van Rossumc6360141990-10-13 19:23:40 +0000222 else: s = `x`
223 n = len(s)
224 if n >= width: return s
225 sign = ''
Guido van Rossum333c2e01991-08-16 13:29:03 +0000226 if s[0] in ('-', '+'):
227 sign, s = s[0], s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000228 return sign + '0'*(width-n) + s
Guido van Rossum6ff2e901992-03-27 15:13:31 +0000229
230# Expand tabs in a string.
231# Doesn't take non-printing chars into account, but does understand \n.
232def expandtabs(s, tabsize):
233 res = line = ''
234 for c in s:
235 if c == '\t':
236 c = ' '*(tabsize - len(line)%tabsize)
237 line = line + c
238 if c == '\n':
239 res = res + line
240 line = ''
241 return res + line
Guido van Rossum2db91351992-10-18 17:09:59 +0000242
243
244# Try importing optional built-in module "strop" -- if it exists,
245# it redefines some string operations that are 100-1000 times faster.
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000246# It also defines values for whitespace, lowercase and uppercase
247# that match <ctype.h>'s definitions.
Guido van Rossum2db91351992-10-18 17:09:59 +0000248
249try:
250 from strop import *
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000251 letters = lowercase + uppercase
Guido van Rossumb6775db1994-08-01 11:34:53 +0000252except ImportError:
253 pass # Use the original, slow versions
254
255# If certain functions are found, redefine the corresponding exceptions
256# as ValueError
257
258try:
Guido van Rossum2db91351992-10-18 17:09:59 +0000259 from strop import index
260 index_error = ValueError
261except ImportError:
262 pass # Use the original, slow versions
Guido van Rossumb6775db1994-08-01 11:34:53 +0000263
264try:
265 from strop import atoi
266 atoi_error = ValueError
267except ImportError:
268 pass # Use the original, slow versions
269
270try:
271 from strop import atof
272 atof_error = ValueError
273except ImportError:
274 pass # Use the original, slow versions
275
276try:
277 from strop import atol
278 atol_error = ValueError
279except ImportError:
280 pass # Use the original, slow versions