blob: afe5bec4cada6a9ffe6cac4e56771a092ba410d3 [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]
Guido van Rossume65cce51993-11-08 15:05:21 +0000103 if i < 0: i = i + len(s)
Guido van Rossumc629d341992-11-05 10:43:02 +0000104 else:
105 i = 0
Guido van Rossumc6360141990-10-13 19:23:40 +0000106 n = len(sub)
Guido van Rossumc629d341992-11-05 10:43:02 +0000107 m = len(s) + 1 - n
108 while i < m:
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000109 if sub == s[i:i+n]: return i
Guido van Rossumc629d341992-11-05 10:43:02 +0000110 i = i+1
Guido van Rossumd3166071993-05-24 14:16:22 +0000111 raise index_error, (s, sub) + args
112
Guido van Rossume65cce51993-11-08 15:05:21 +0000113# Find last substring, raise exception if not found
114def rindex(s, sub, *args):
115 if args:
116 if len(args) > 1:
117 raise TypeError, 'string.rindex(): too many args'
118 i = args[0]
119 if i < 0: i = i + len(s)
120 else:
121 i = 0
122 n = len(sub)
123 m = len(s) + 1 - n
124 r = None
125 while i < m:
126 if sub == s[i:i+n]: r = i
127 i = i+1
128 if r is None:
129 raise index_error, (s, sub) + args
130 return r
131
Guido van Rossumd3166071993-05-24 14:16:22 +0000132# Find substring, return -1 if not found
133def find(*args):
134 try:
135 return apply(index, args)
136 except index_error:
137 return -1
Guido van Rossumc6360141990-10-13 19:23:40 +0000138
Guido van Rossume65cce51993-11-08 15:05:21 +0000139# Find last substring, return -1 if not found
140def rfind(*args):
141 try:
142 return apply(rindex, args)
143 except index_error:
144 return -1
145
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000146# Convert string to float
147atof_error = 'non-float argument to string.atof'
148def atof(str):
149 import regex
150 sign = ''
151 s = str
152 if s and s[0] in '+-':
153 sign = s[0]
154 s = s[1:]
155 if not s: raise atof_error, str
156 while s[0] == '0' and len(s) > 1 and s[1] in digits: s = s[1:]
157 if regex.match('[0-9]*\(\.[0-9]*\)?\([eE][-+]?[0-9]+\)?', s) != len(s):
158 raise atof_error, str
159 try:
160 return eval(sign + s)
161 except SyntaxError:
162 raise atof_error, str
163
Guido van Rossumc6360141990-10-13 19:23:40 +0000164# Convert string to integer
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000165atoi_error = 'non-integer argument to string.atoi'
Guido van Rossumc6360141990-10-13 19:23:40 +0000166def atoi(str):
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000167 sign = ''
Guido van Rossumc6360141990-10-13 19:23:40 +0000168 s = str
Guido van Rossumc629d341992-11-05 10:43:02 +0000169 if s and s[0] in '+-':
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000170 sign = s[0]
171 s = s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000172 if not s: raise atoi_error, str
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000173 while s[0] == '0' and len(s) > 1: s = s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000174 for c in s:
175 if c not in digits: raise atoi_error, str
Guido van Rossum2d4aa4f1992-08-06 22:33:41 +0000176 return eval(sign + s)
Guido van Rossumc6360141990-10-13 19:23:40 +0000177
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000178# Convert string to long integer
179atol_error = 'non-integer argument to string.atol'
180def atol(str):
181 sign = ''
182 s = str
183 if s and s[0] in '+-':
184 sign = s[0]
185 s = s[1:]
186 if not s: raise atoi_error, str
187 while s[0] == '0' and len(s) > 1: s = s[1:]
188 for c in s:
189 if c not in digits: raise atoi_error, str
190 return eval(sign + s + 'L')
191
Guido van Rossumc6360141990-10-13 19:23:40 +0000192# Left-justify a string
193def ljust(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000194 n = width - len(s)
195 if n <= 0: return s
196 return s + ' '*n
Guido van Rossumc6360141990-10-13 19:23:40 +0000197
198# Right-justify a string
199def rjust(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000200 n = width - len(s)
201 if n <= 0: return s
202 return ' '*n + s
Guido van Rossumc6360141990-10-13 19:23:40 +0000203
204# Center a string
205def center(s, width):
Guido van Rossumfac38b71991-04-07 13:42:19 +0000206 n = width - len(s)
207 if n <= 0: return s
208 half = n/2
209 if n%2 and width%2:
210 # This ensures that center(center(s, i), j) = center(s, j)
211 half = half+1
212 return ' '*half + s + ' '*(n-half)
Guido van Rossumc6360141990-10-13 19:23:40 +0000213
214# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
215# Decadent feature: the argument may be a string or a number
216# (Use of this is deprecated; it should be a string as with ljust c.s.)
217def zfill(x, width):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +0000218 if type(x) == type(''): s = x
Guido van Rossumc6360141990-10-13 19:23:40 +0000219 else: s = `x`
220 n = len(s)
221 if n >= width: return s
222 sign = ''
Guido van Rossum333c2e01991-08-16 13:29:03 +0000223 if s[0] in ('-', '+'):
224 sign, s = s[0], s[1:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000225 return sign + '0'*(width-n) + s
Guido van Rossum6ff2e901992-03-27 15:13:31 +0000226
227# Expand tabs in a string.
228# Doesn't take non-printing chars into account, but does understand \n.
229def expandtabs(s, tabsize):
230 res = line = ''
231 for c in s:
232 if c == '\t':
233 c = ' '*(tabsize - len(line)%tabsize)
234 line = line + c
235 if c == '\n':
236 res = res + line
237 line = ''
238 return res + line
Guido van Rossum2db91351992-10-18 17:09:59 +0000239
240
241# Try importing optional built-in module "strop" -- if it exists,
242# it redefines some string operations that are 100-1000 times faster.
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000243# It also defines values for whitespace, lowercase and uppercase
244# that match <ctype.h>'s definitions.
Guido van Rossum2db91351992-10-18 17:09:59 +0000245# The manipulation with index_error is needed for compatibility.
246
247try:
248 from strop import *
Guido van Rossum8e2ec561993-07-29 09:37:38 +0000249 letters = lowercase + uppercase
Guido van Rossum2db91351992-10-18 17:09:59 +0000250 from strop import index
251 index_error = ValueError
252except ImportError:
253 pass # Use the original, slow versions