String method conversion.

This commit is contained in:
Eric S. Raymond 2001-02-09 11:10:16 +00:00
parent be9b507bdd
commit b08b2d3166
6 changed files with 35 additions and 38 deletions

View File

@ -157,7 +157,7 @@ class AbstractFormatter:
label = s + label label = s + label
index = index + 1 index = index + 1
if case == 'I': if case == 'I':
return string.upper(label) return label.upper()
return label return label
def add_flowing_data(self, data, def add_flowing_data(self, data,
@ -369,11 +369,11 @@ class DumbWriter(NullWriter):
def send_literal_data(self, data): def send_literal_data(self, data):
self.file.write(data) self.file.write(data)
i = string.rfind(data, '\n') i = data.rfind('\n')
if i >= 0: if i >= 0:
self.col = 0 self.col = 0
data = data[i+1:] data = data[i+1:]
data = string.expandtabs(data) data = data.expandtabs()
self.col = self.col + len(data) self.col = self.col + len(data)
self.atbreak = 0 self.atbreak = 0
@ -383,7 +383,7 @@ class DumbWriter(NullWriter):
col = self.col col = self.col
maxcol = self.maxcol maxcol = self.maxcol
write = self.file.write write = self.file.write
for word in string.split(data): for word in data.split():
if atbreak: if atbreak:
if col + len(word) >= maxcol: if col + len(word) >= maxcol:
write('\n') write('\n')

View File

@ -19,15 +19,15 @@ def url2pathname(url):
# convert this to \\host\path\on\remote\host # convert this to \\host\path\on\remote\host
# (notice halving of slashes at the start of the path) # (notice halving of slashes at the start of the path)
url = url[2:] url = url[2:]
components = string.split(url, '/') components = url.split('/')
# make sure not to convert quoted slashes :-) # make sure not to convert quoted slashes :-)
return urllib.unquote(string.join(components, '\\')) return urllib.unquote('\\'.join(components))
comp = string.split(url, '|') comp = url.split('|')
if len(comp) != 2 or comp[0][-1] not in string.letters: if len(comp) != 2 or comp[0][-1] not in string.letters:
error = 'Bad URL: ' + url error = 'Bad URL: ' + url
raise IOError, error raise IOError, error
drive = string.upper(comp[0][-1]) drive = comp[0][-1].upper()
components = string.split(comp[1], '/') components = comp[1].split('/')
path = drive + ':' path = drive + ':'
for comp in components: for comp in components:
if comp: if comp:
@ -52,15 +52,15 @@ def pathname2url(p):
# convert this to ////host/path/on/remote/host # convert this to ////host/path/on/remote/host
# (notice doubling of slashes at the start of the path) # (notice doubling of slashes at the start of the path)
p = '\\\\' + p p = '\\\\' + p
components = string.split(p, '\\') components = p.split('\\')
return urllib.quote(string.join(components, '/')) return urllib.quote('/'.join(components))
comp = string.split(p, ':') comp = p.split(':')
if len(comp) != 2 or len(comp[0]) > 1: if len(comp) != 2 or len(comp[0]) > 1:
error = 'Bad path: ' + p error = 'Bad path: ' + p
raise IOError, error raise IOError, error
drive = urllib.quote(string.upper(comp[0])) drive = urllib.quote(comp[0].upper())
components = string.split(comp[1], '\\') components = comp[1].split('\\')
path = '///' + drive + '|' path = '///' + drive + '|'
for comp in components: for comp in components:
if comp: if comp:

View File

@ -17,8 +17,6 @@
import sre_compile import sre_compile
import sre_parse import sre_parse
import string
# flags # flags
I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
@ -109,7 +107,7 @@ _MAXCACHE = 100
def _join(seq, sep): def _join(seq, sep):
# internal: join into string having the same type as sep # internal: join into string having the same type as sep
return string.join(seq, sep[:0]) return sep[:0].join(seq)
def _compile(*key): def _compile(*key):
# internal: compile pattern # internal: compile pattern

View File

@ -94,7 +94,7 @@ def main():
except IOError, err: except IOError, err:
sys.stdout.write("I/O error: %s\n" % str(err)) sys.stdout.write("I/O error: %s\n" % str(err))
sys.exit(1) sys.exit(1)
lines = string.splitfields(fp.read(), "\n") lines = fp.read().split("\n")
fp.close() fp.close()
prog = re.compile( prog = re.compile(
"#define[ \t][ \t]*([A-Z][A-Z_]*)[ \t][ \t]*([0-9][0-9]*)", "#define[ \t][ \t]*([A-Z][A-Z_]*)[ \t][ \t]*([0-9][0-9]*)",
@ -114,7 +114,7 @@ def main():
except IOError, err: except IOError, err:
sys.stderr.write("I/O error: %s\n" % str(err)) sys.stderr.write("I/O error: %s\n" % str(err))
sys.exit(2) sys.exit(2)
format = string.splitfields(fp.read(), "\n") format = fp.read().split("\n")
fp.close() fp.close()
try: try:
start = format.index("#--start constants--") + 1 start = format.index("#--start constants--") + 1
@ -131,7 +131,7 @@ def main():
except IOError, err: except IOError, err:
sys.stderr.write("I/O error: %s\n" % str(err)) sys.stderr.write("I/O error: %s\n" % str(err))
sys.exit(4) sys.exit(4)
fp.write(string.joinfields(format, "\n")) fp.write("\n".join(format))
fp.close() fp.close()

View File

@ -26,7 +26,7 @@ tok_name[NL] = 'NL'
# Imagnumber is new. Expfloat is corrected to reject '0e4'. # Imagnumber is new. Expfloat is corrected to reject '0e4'.
# Note: to quote a backslash in a regex, it must be doubled in a r'aw' string. # Note: to quote a backslash in a regex, it must be doubled in a r'aw' string.
def group(*choices): return '(' + string.join(choices, '|') + ')' def group(*choices): return '(' + '|'.join(choices) + ')'
def any(*choices): return apply(group, choices) + '*' def any(*choices): return apply(group, choices) + '*'
def maybe(*choices): return apply(group, choices) + '?' def maybe(*choices): return apply(group, choices) + '?'

View File

@ -85,7 +85,6 @@ f = urllib2.urlopen('http://www.python.org/')
# gopher can return a socket.error # gopher can return a socket.error
# check digest against correct (i.e. non-apache) implementation # check digest against correct (i.e. non-apache) implementation
import string
import socket import socket
import UserDict import UserDict
import httplib import httplib
@ -265,13 +264,13 @@ class OpenerDirector:
self.handle_open[protocol] = [handler] self.handle_open[protocol] = [handler]
added = 1 added = 1
continue continue
i = string.find(meth, '_') i = meth.find('_')
j = string.find(meth[i+1:], '_') + i + 1 j = meth[i+1:].find('_') + i + 1
if j != -1 and meth[i+1:j] == 'error': if j != -1 and meth[i+1:j] == 'error':
proto = meth[:i] proto = meth[:i]
kind = meth[j+1:] kind = meth[j+1:]
try: try:
kind = string.atoi(kind) kind = int(kind)
except ValueError: except ValueError:
pass pass
dict = self.handle_error.get(proto, {}) dict = self.handle_error.get(proto, {})
@ -599,7 +598,7 @@ class HTTPBasicAuthHandler(BaseHandler):
mo = HTTPBasicAuthHandler.rx.match(authreq) mo = HTTPBasicAuthHandler.rx.match(authreq)
if mo: if mo:
scheme, realm = mo.groups() scheme, realm = mo.groups()
if string.lower(scheme) == 'basic': if scheme.lower() == 'basic':
return self.retry_http_basic_auth(req, realm) return self.retry_http_basic_auth(req, realm)
def retry_http_basic_auth(self, req, realm): def retry_http_basic_auth(self, req, realm):
@ -613,7 +612,7 @@ class HTTPBasicAuthHandler(BaseHandler):
user,pw = self.passwd.find_user_password(realm, host) user,pw = self.passwd.find_user_password(realm, host)
if pw: if pw:
raw = "%s:%s" % (user, pw) raw = "%s:%s" % (user, pw)
auth = string.strip(base64.encodestring(raw)) auth = base64.encodestring(raw).strip()
req.add_header('Authorization', 'Basic %s' % auth) req.add_header('Authorization', 'Basic %s' % auth)
resp = self.parent.open(req) resp = self.parent.open(req)
self.__current_realm = None self.__current_realm = None
@ -638,12 +637,12 @@ class HTTPDigestAuthHandler(BaseHandler):
# XXX could be mult. headers # XXX could be mult. headers
authreq = headers.get('www-authenticate', None) authreq = headers.get('www-authenticate', None)
if authreq: if authreq:
kind = string.split(authreq)[0] kind = authreq.split()[0]
if kind == 'Digest': if kind == 'Digest':
return self.retry_http_digest_auth(req, authreq) return self.retry_http_digest_auth(req, authreq)
def retry_http_digest_auth(self, req, auth): def retry_http_digest_auth(self, req, auth):
token, challenge = string.split(auth, ' ', 1) token, challenge = auth.split(' ', 1)
chal = parse_keqv_list(parse_http_list(challenge)) chal = parse_keqv_list(parse_http_list(challenge))
auth = self.get_authorization(req, chal) auth = self.get_authorization(req, chal)
if auth: if auth:
@ -723,7 +722,7 @@ def encode_digest(digest):
hexrep.append(hex(n)[-1]) hexrep.append(hex(n)[-1])
n = ord(c) & 0xf n = ord(c) & 0xf
hexrep.append(hex(n)[-1]) hexrep.append(hex(n)[-1])
return string.join(hexrep, '') return ''.join(hexrep)
class HTTPHandler(BaseHandler): class HTTPHandler(BaseHandler):
@ -772,7 +771,7 @@ def parse_keqv_list(l):
"""Parse list of key=value strings where keys are not duplicated.""" """Parse list of key=value strings where keys are not duplicated."""
parsed = {} parsed = {}
for elt in l: for elt in l:
k, v = string.split(elt, '=', 1) k, v = elt.split('=', 1)
if v[0] == '"' and v[-1] == '"': if v[0] == '"' and v[-1] == '"':
v = v[1:-1] v = v[1:-1]
parsed[k] = v parsed[k] = v
@ -794,8 +793,8 @@ def parse_http_list(s):
start = 0 start = 0
while i < end: while i < end:
cur = s[i:] cur = s[i:]
c = string.find(cur, ',') c = cur.find(',')
q = string.find(cur, '"') q = cur.find('"')
if c == -1: if c == -1:
list.append(s[start:]) list.append(s[start:])
break break
@ -822,7 +821,7 @@ def parse_http_list(s):
else: else:
inquote = 1 inquote = 1
i = i + q + 1 i = i + q + 1
return map(string.strip, list) return map(lambda x: x.strip(), list)
class FileHandler(BaseHandler): class FileHandler(BaseHandler):
# Use local file or FTP depending on form of URL # Use local file or FTP depending on form of URL
@ -872,7 +871,7 @@ class FTPHandler(BaseHandler):
port = ftplib.FTP_PORT port = ftplib.FTP_PORT
path, attrs = splitattr(req.get_selector()) path, attrs = splitattr(req.get_selector())
path = unquote(path) path = unquote(path)
dirs = string.splitfields(path, '/') dirs = path.split('/')
dirs, file = dirs[:-1], dirs[-1] dirs, file = dirs[:-1], dirs[-1]
if dirs and not dirs[0]: if dirs and not dirs[0]:
dirs = dirs[1:] dirs = dirs[1:]
@ -882,9 +881,9 @@ class FTPHandler(BaseHandler):
type = file and 'I' or 'D' type = file and 'I' or 'D'
for attr in attrs: for attr in attrs:
attr, value = splitattr(attr) attr, value = splitattr(attr)
if string.lower(attr) == 'type' and \ if attr.lower() == 'type' and \
value in ('a', 'A', 'i', 'I', 'd', 'D'): value in ('a', 'A', 'i', 'I', 'd', 'D'):
type = string.upper(value) type = value.upper()
fp, retrlen = fw.retrfile(file, type) fp, retrlen = fw.retrfile(file, type)
if retrlen is not None and retrlen >= 0: if retrlen is not None and retrlen >= 0:
sf = StringIO('Content-Length: %d\n' % retrlen) sf = StringIO('Content-Length: %d\n' % retrlen)
@ -1048,7 +1047,7 @@ if __name__ == "__main__":
p = CustomProxy('http', at_cnri, 'proxy.cnri.reston.va.us') p = CustomProxy('http', at_cnri, 'proxy.cnri.reston.va.us')
ph = CustomProxyHandler(p) ph = CustomProxyHandler(p)
install_opener(build_opener(dauth, bauth, cfh, GopherHandler, ph)) #install_opener(build_opener(dauth, bauth, cfh, GopherHandler, ph))
for url in urls: for url in urls:
if type(url) == types.TupleType: if type(url) == types.TupleType: