(original) (raw)
Index: Lib/CGIHTTPServer.py =================================================================== --- Lib/CGIHTTPServer.py (revision 51511) +++ Lib/CGIHTTPServer.py (working copy) @@ -106,12 +106,14 @@ def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info - i = rest.rfind('?') + try:i = rest.rindex('?') + except: i = -1 if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' - i = rest.find('/') + try:i = rest.index('/') + except:i=-1 if i >= 0: script, rest = rest[:i], rest[i:] else: Index: Lib/markupbase.py =================================================================== --- Lib/markupbase.py (revision 51511) +++ Lib/markupbase.py (working copy) @@ -249,9 +249,10 @@ return -1 # style content model; just skip until '>' rawdata = self.rawdata - if '>' in rawdata[j:]: - return rawdata.find(">", j) + 1 - return -1 + try: + return rawdata.index(">", j) + 1 + except ValueError: + return -1 # Internal -- scan past 0: Index: Lib/mimetypes.py =================================================================== --- Lib/mimetypes.py (revision 51511) +++ Lib/mimetypes.py (working copy) @@ -112,11 +112,13 @@ # data := *urlchar # parameter := attribute "=" value # type/subtype defaults to "text/plain" - comma = url.find(',') + try:comma = url.index(',') + except: comma = -1 if comma < 0: # bad data URL return None, None - semi = url.find(';', 0, comma) + try:semi = url.index(';', 0, comma) + except: semi = -1 if semi >= 0: type = url[:semi] else: Index: Lib/idlelib/AutoComplete.py =================================================================== --- Lib/idlelib/AutoComplete.py (revision 51511) +++ Lib/idlelib/AutoComplete.py (working copy) @@ -140,7 +140,9 @@ hp.set_index("insert-%dc" % (len(curline)-(i-1))) comp_what = hp.get_expression() if not comp_what or \ - (not evalfuncs and comp_what.find('(') != -1): + try:openparensposition = comp_what.index('(') + except:openparensposition=-1 + (not evalfuncs and openparensposition != -1): return else: comp_what = "" Index: Lib/idlelib/configHandler.py =================================================================== --- Lib/idlelib/configHandler.py (revision 51511) +++ Lib/idlelib/configHandler.py (working copy) @@ -629,10 +629,10 @@ options=cfgParser.GetOptionList('HelpFiles') for option in options: value=cfgParser.Get('HelpFiles',option,default=';') - if value.find(';')==-1: #malformed config entry with no ';' + try:value.index(';')==-1: #malformed config entry with no ';' menuItem='' #make these empty helpPath='' #so value won't be added to list - else: #config entry contains ';' as expected + except: #config entry contains ';' as expected value=string.split(value,';') menuItem=value[0].strip() helpPath=value[1].strip() Index: Lib/idlelib/EditorWindow.py =================================================================== --- Lib/idlelib/EditorWindow.py (revision 51511) +++ Lib/idlelib/EditorWindow.py (working copy) @@ -556,7 +556,9 @@ f.close() except IOError: return False - return line.startswith('#!') and line.find('python') >= 0 + try:pythonpos=line.index('python') + except:pythonpos = -1 + return line.startswith('#!') and pythonpos>= 0 def close_hook(self): if self.flist: @@ -1456,7 +1458,8 @@ def prepstr(s): # Helper to extract the underscore from a string, e.g. # prepstr("Co_py") returns (2, "Copy"). - i = s.find('_') + try:i = s.index('_') + except:i=-1 if i >= 0: s = s[:i] + s[i+1:] return i, s Index: Lib/idlelib/PyParse.py =================================================================== --- Lib/idlelib/PyParse.py (revision 51511) +++ Lib/idlelib/PyParse.py (working copy) @@ -157,10 +157,12 @@ # bumped to a legitimate synch point. limit = len(str) for tries in range(5): - i = str.rfind(":\n", 0, limit) + try:i = str.rindex(":\n", 0, limit) + except: i = -1 if i < 0: break - i = str.rfind('\n', 0, i) + 1 # start of colon line + try:i = str.rindex('\n', 0, i) + 1 # start of colon line + except:i=-1 m = _synchre(str, i, limit) if m and not is_char_in_string(m.start()): pos = m.start() @@ -307,7 +309,8 @@ if ch == '#': # consume the comment - i = str.find('\n', i) + try:i = str.index('\n', i) + except: i = -1 assert i >= 0 continue @@ -371,7 +374,8 @@ q = p for nothing in range(goodlines[i-1], goodlines[i]): # tricky: sets p to 0 if no preceding newline - p = str.rfind('\n', 0, p-1) + 1 + try:p = str.rindex('\n', 0, p-1) + 1 + except:p=-1 # The stmt str[p:q] isn't a continuation, but may be blank # or a non-indenting comment line. if _junkre(str, p): @@ -440,7 +444,8 @@ if ch == '#': # consume comment and trailing newline bracketing.append((p, len(stack)+1)) - p = str.find('\n', p, q) + 1 + try:p = str.index('\n', p, q) + 1 + except: p = -1 assert p > 0 bracketing.append((p, len(stack))) continue @@ -469,7 +474,10 @@ j = self.lastopenbracketpos str = self.str n = len(str) - origi = i = str.rfind('\n', 0, j) + 1 + try:origi = i = str.rindex('\n', 0, j) + except: origi=i=-1 + origi+=1 + i+=1 j = j+1 # one beyond open bracket # find first list item; set i to start of its line while j < n: @@ -480,7 +488,9 @@ break else: # this line is junk; advance to next line - i = j = str.find('\n', j) + 1 + try:i = j = str.index('\n', j) + except: i = j = -1 + i,j=i+1,j+1 else: # nothing interesting follows the bracket; # reproduce the bracket line's indentation + a level @@ -514,7 +524,8 @@ # See whether the initial line starts an assignment stmt; i.e., # look for an = operator - endpos = str.find('\n', startpos) + 1 + try:endpos = str.index('\n', startpos) + 1 + except:endpos = -1 found = level = 0 while i < endpos: ch = str[i] Index: Lib/idlelib/CallTips.py =================================================================== --- Lib/idlelib/CallTips.py (revision 51511) +++ Lib/idlelib/CallTips.py (working copy) @@ -70,8 +70,9 @@ return hp.set_index(sur_paren[0]) name = hp.get_expression() - if not name or (not evalfuncs and name.find('(') != -1): - return + if not name: + try: (not evalfuncs and name.index('(') != -1): + except: return arg_text = self.fetch_tip(name) if not arg_text: return @@ -161,7 +162,8 @@ doc = getattr(ob, "__doc__", "") if doc: doc = doc.lstrip() - pos = doc.find("\n") + try:pos = doc.index("\n") + except:pos=-1 if pos < 0 or pos > 70: pos = 70 if argText: Index: Lib/os.py =================================================================== --- Lib/os.py (revision 51511) +++ Lib/os.py (working copy) @@ -74,7 +74,9 @@ from os2 import _exit except ImportError: pass - if sys.version.find('EMX GCC') == -1: + try:emx_version=sys.version.index('EMX GCC') + except:emx_version=-1 + if emx_version == -1: import ntpath as path else: import os2emxpath as path Index: Lib/smtpd.py =================================================================== --- Lib/smtpd.py (revision 51511) +++ Lib/smtpd.py (working copy) @@ -144,7 +144,8 @@ self.push('500 Error: bad syntax') return method = None - i = line.find(' ') + try:i = line.index(' ') + except: i = -1 if i < 0: command = line.upper() arg = None @@ -495,7 +496,8 @@ usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args)) # split into host/port pairs - i = localspec.find(':') + try:i = localspec.index(':') + except: i=-1 if i < 0: usage(1, 'Bad local spec: %s' % localspec) options.localhost = localspec[:i] @@ -503,7 +505,8 @@ options.localport = int(localspec[i+1:]) except ValueError: usage(1, 'Bad local port: %s' % localspec) - i = remotespec.find(':') + try:i = remotespec.index(':') + except: i = -1 if i < 0: usage(1, 'Bad remote spec: %s' % remotespec) options.remotehost = remotespec[:i] @@ -535,7 +538,8 @@ sys.exit(1) classname = options.classname if "." in classname: - lastdot = classname.rfind(".") + try:lastdot = classname.rindex(".") + except:lastdot=-1 mod = __import__(classname[:lastdot], globals(), locals(), [""]) classname = classname[lastdot+1:] else: Index: Lib/stringold.py =================================================================== --- Lib/stringold.py (revision 51511) +++ Lib/stringold.py (working copy) @@ -155,32 +155,6 @@ """ return s.count(*args) -# Find substring, return -1 if not found -def find(s, *args): - """find(s, sub [,start [,end]]) -> in - - Return the lowest index in s where substring sub is found, - such that sub is contained within s[start,end]. Optional - arguments start and end are interpreted as in slice notation. - - Return -1 on failure. - - """ - return s.find(*args) - -# Find last substring, return -1 if not found -def rfind(s, *args): - """rfind(s, sub [,start [,end]]) -> int - - Return the highest index in s where substring sub is found, - such that sub is contained within s[start,end]. Optional - arguments start and end are interpreted as in slice notation. - - Return -1 on failure. - - """ - return s.rfind(*args) - # for a bit of speed _float = float _int = int Index: Lib/smtplib.py =================================================================== --- Lib/smtplib.py (revision 51511) +++ Lib/smtplib.py (working copy) @@ -282,8 +282,12 @@ specified during instantiation. """ - if not port and (host.find(':') == host.rfind(':')): - i = host.rfind(':') + try:first_colon = host.index(':') + except: first_colon = -1 + try:last_colon = host.rindex(':') + except: last_colon=-1 + if not port and (first_colon == last_colon): + i = last_colon if i >= 0: host, port = host[:i], host[i+1:] try: port = int(port) Index: Lib/posixpath.py =================================================================== --- Lib/posixpath.py (revision 51511) +++ Lib/posixpath.py (working copy) @@ -74,7 +74,9 @@ def split(p): """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty.""" - i = p.rfind('/') + 1 + try:i = p.rindex('/') + except: i = -1 + finally: i += 1 head, tail = p[:i], p[i:] if head and head != '/'*len(head): head = head.rstrip('/') @@ -89,8 +91,11 @@ def splitext(p): """Split the extension from a pathname. Extension is everything from the last dot to the end. Returns "(root, ext)", either part may be empty.""" - i = p.rfind('.') - if i<=p.rfind('/'): + try:i = p.rindex('.') + except: i = -1 + try: slash_index = p.rindex('/') + except: slash_index = -1 + if i<=slash_index: return p, '' else: return p[:i], p[i:] @@ -312,7 +317,8 @@ do nothing.""" if not path.startswith('~'): return path - i = path.find('/', 1) + try:i = path.index('/', 1) + except: i = -1 if i < 0: i = len(path) if i == 1: Index: Lib/warnings.py =================================================================== --- Lib/warnings.py (revision 51511) +++ Lib/warnings.py (working copy) @@ -243,7 +243,10 @@ except NameError: raise _OptionError("unknown warning category: %r" % (category,)) else: - i = category.rfind(".") + try: + i = category.rindex(".") + except ValueError: + i = -1 module = category[:i] klass = category[i+1:] try: Index: Lib/distutils/extension.py =================================================================== --- Lib/distutils/extension.py (revision 51511) +++ Lib/distutils/extension.py (working copy) @@ -195,7 +195,8 @@ elif switch == "-I": ext.include_dirs.append(value) elif switch == "-D": - equals = string.find(value, "=") + try:equals = string.index(value, "=") + except: equals = -1 if equals == -1: # bare "-DFOO" -- no value ext.define_macros.append((value, None)) else: # "-DFOO=blah" Index: Lib/distutils/text_file.py =================================================================== --- Lib/distutils/text_file.py (revision 51511) +++ Lib/distutils/text_file.py (working copy) @@ -196,7 +196,9 @@ # unescape it (and any other escaped "#"'s that might be # lurking in there) and otherwise leave the line alone. - pos = string.find (line, "#") + + try:pos = string.index (line, "#") + except: pos=-1 if pos == -1: # no "#" -- no comments pass Index: Lib/distutils/command/build_ext.py =================================================================== --- Lib/distutils/command/build_ext.py (revision 51511) +++ Lib/distutils/command/build_ext.py (working copy) @@ -188,7 +188,9 @@ if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos' or \ (sys.platform.startswith('linux') and sysconfig.get_config_var('Py_ENABLE_SHARED')): - if string.find(sys.executable, sys.exec_prefix) != -1: + try:prefixloc=string.index(sys.executable, sys.exec_prefix) + except: prefixloc=-1 + if prefixloc != -1: # building third party extensions self.library_dirs.append(os.path.join(sys.prefix, "lib", "python" + get_python_version(), Index: Lib/formatter.py =================================================================== --- Lib/formatter.py (revision 51511) +++ Lib/formatter.py (working copy) @@ -394,7 +394,8 @@ def send_literal_data(self, data): self.file.write(data) - i = data.rfind('\n') + try:i = data.rindex('\n') + except: i = -1 if i >= 0: self.col = 0 data = data[i+1:] Index: Lib/mailcap.py =================================================================== --- Lib/mailcap.py (revision 51511) +++ Lib/mailcap.py (working copy) @@ -105,7 +105,8 @@ key, view, rest = fields[0], fields[1], fields[2:] fields = {'view': view} for field in rest: - i = field.find('=') + try:i = field.index('=') + except:i=-1 if i < 0: fkey = field fvalue = "" Index: Lib/gzip.py =================================================================== --- Lib/gzip.py (revision 51511) +++ Lib/gzip.py (working copy) @@ -397,7 +397,8 @@ bufs = [] while size != 0: c = self.read(readsize) - i = c.find('\n') + try:i = c.index('\n') + except: i = -1 # We set i=size to break out of the loop under two # conditions: 1) there's no newline, and the chunk is Index: Lib/gopherlib.py =================================================================== --- Lib/gopherlib.py (revision 51511) +++ Lib/gopherlib.py (working copy) @@ -61,7 +61,8 @@ """Send a selector to a given host and port, return a file with the reply.""" import socket if not port: - i = host.find(':') + try:i = host.index(':') + except:i=-1 if i >= 0: host, port = host[:i], int(host[i+1:]) if not port: Index: Lib/modulefinder.py =================================================================== --- Lib/modulefinder.py (revision 51511) +++ Lib/modulefinder.py (working copy) @@ -141,7 +141,8 @@ self.msgout(4, "determine_parent ->", parent) return parent if '.' in pname: - i = pname.rfind('.') + try:i = pname.rindex('.') + except:i=-1 pname = pname[:i] parent = self.modules[pname] assert parent.__name__ == pname @@ -153,7 +154,8 @@ def find_head_package(self, parent, name): self.msgin(4, "find_head_package", parent, name) if '.' in name: - i = name.find('.') + try:i = name.index('.') + except:i=-1 head = name[:i] tail = name[i+1:] else: @@ -181,7 +183,8 @@ self.msgin(4, "load_tail", q, tail) m = q while tail: - i = tail.find('.') + try:i = tail.index('.') + except: i = -1 if i < 0: i = len(tail) head, tail = tail[:i], tail[i+1:] mname = "%s.%s" % (m.__name__, head) @@ -469,7 +472,8 @@ for name in self.badmodules: if name in self.excludes: continue - i = name.rfind(".") + try:i = name.rindex(".") + except:i=-1 if i < 0: missing.append(name) continue Index: Lib/macpath.py =================================================================== --- Lib/macpath.py (revision 51511) +++ Lib/macpath.py (working copy) @@ -73,8 +73,11 @@ pathname component; the root is everything before that. It is always true that root + ext == p.""" - i = p.rfind('.') - if i<=p.rfind(':'): + try: i = p.rindex('.') + except: i =-1 + try: i2 = p.rindex(':') + except:i2=-1 + if i<=i2 return p, '' else: return p[:i], p[i:] Index: Lib/ftplib.py =================================================================== --- Lib/ftplib.py (revision 51511) +++ Lib/ftplib.py (working copy) @@ -584,9 +584,11 @@ if resp[:3] != '229': raise error_reply, resp - left = resp.find('(') + try:left = resp.index('(') + except: left = -1 if left < 0: raise error_proto, resp - right = resp.find(')', left + 1) + try:right = resp.index(')', left + 1) + except: right = -1 if right < 0: raise error_proto, resp # should contain '(|||port|)' if resp[left + 1] != resp[right - 1]: Index: Lib/socket.py =================================================================== --- Lib/socket.py (revision 51511) +++ Lib/socket.py (working copy) @@ -332,7 +332,8 @@ break buffers.append(data) return "".join(buffers) - nl = data.find('\n') + try: nl = data.index('\n') + except: nl = -1 if nl >= 0: nl += 1 self._rbuf = data[nl:] @@ -346,7 +347,8 @@ if not data: break buffers.append(data) - nl = data.find('\n') + try:nl = data.index('\n') + except: nl=-1 if nl >= 0: nl += 1 self._rbuf = data[nl:] @@ -355,7 +357,8 @@ return "".join(buffers) else: # Read until size bytes or \n or EOF seen, whichever comes first - nl = data.find('\n', 0, size) + try:nl = data.index('\n', 0, size) + except: nl=-1 if nl >= 0: nl += 1 self._rbuf = data[nl:] @@ -374,7 +377,8 @@ break buffers.append(data) left = size - buf_len - nl = data.find('\n', 0, left) + try:nl = data.index('\n', 0, left) + except:nl=-1 if nl >= 0: nl += 1 self._rbuf = data[nl:] Index: Lib/ihooks.py =================================================================== --- Lib/ihooks.py (revision 51511) +++ Lib/ihooks.py (working copy) @@ -418,7 +418,8 @@ assert globals is parent.__dict__ return parent if '.' in pname: - i = pname.rfind('.') + try:i = pname.rindex('.') + except:i=-1 pname = pname[:i] parent = self.modules[pname] assert parent.__name__ == pname @@ -427,7 +428,8 @@ def find_head_package(self, parent, name): if '.' in name: - i = name.find('.') + try:i = name.index('.') + except:i=-1 head = name[:i] tail = name[i+1:] else: @@ -449,7 +451,8 @@ def load_tail(self, q, tail): m = q while tail: - i = tail.find('.') + try:i = tail.index('.') + except:i=-1 if i < 0: i = len(tail) head, tail = tail[:i], tail[i+1:] mname = "%s.%s" % (m.__name__, head) @@ -501,7 +504,8 @@ name = str(module.__name__) if '.' not in name: return self.import_it(name, name, None, force_load=1) - i = name.rfind('.') + try:i = name.rindex('.') + except: i = -1 pname = name[:i] parent = self.modules[pname] return self.import_it(name[i+1:], name, parent, force_load=1) Index: Lib/logging/__init__.py =================================================================== --- Lib/logging/__init__.py (revision 51511) +++ Lib/logging/__init__.py (working copy) @@ -416,7 +416,9 @@ formatException() and appended to the message. """ record.message = record.getMessage() - if string.find(self._fmt,"%(asctime)") >= 0: + try: timeloc=string.index(self._fmt, '%(asctime)') + except: timeloc = -1 + if timeloc >= 0: record.asctime = self.formatTime(record, self.datefmt) s = self._fmt % record.__dict__ if record.exc_info: @@ -506,11 +508,13 @@ Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place. """ + try:namepos=string.index(record.name, self.name, 0, self.nlen) + except:namepos = -1 if self.nlen == 0: return 1 elif self.name == record.name: return 1 - elif string.find(record.name, self.name, 0, self.nlen) != 0: + elif namepos != 0: return 0 return (record.name[self.nlen] == ".") @@ -887,7 +891,8 @@ from the specified logger to the root of the logger hierarchy. """ name = alogger.name - i = string.rfind(name, ".") + try:i = string.rindex(name, ".") + except:i=-1 rv = None while (i > 0) and not rv: substr = name[:i] @@ -900,7 +905,8 @@ else: assert isinstance(obj, PlaceHolder) obj.append(alogger) - i = string.rfind(name, ".", 0, i - 1) + try:i = string.rindex(name, ".", 0, i - 1) + except: i = -1 if not rv: rv = self.root alogger.parent = rv @@ -912,7 +918,9 @@ """ #for c in ph.loggers: for c in ph.loggerMap.keys(): - if string.find(c.parent.name, alogger.name) <> 0: + try: parent_name_loc = string.index(c.parent.name, alogger.name) + except: parent_name_loc = -1 + if parent_name_loc <> 0: alogger.parent = c.parent c.parent = alogger Index: Lib/logging/handlers.py =================================================================== --- Lib/logging/handlers.py (revision 51511) +++ Lib/logging/handlers.py (working copy) @@ -896,7 +896,9 @@ url = self.url data = urllib.urlencode(self.mapLogRecord(record)) if self.method == "GET": - if (string.find(url, '?') >= 0): + try: separator_position = string.index(url,'?') + except: separator_position = -1 + if (separator_position >= 0): sep = '&' else: sep = '?' @@ -904,7 +906,8 @@ h.putrequest(self.method, url) # support multiple hosts on one IP address... # need to strip optional :port from host, if present - i = string.find(host, ":") + try:i = string.index(host, ":") + except:i=-1 if i >= 0: host = host[:i] h.putheader("Host", host) Index: Lib/cookielib.py =================================================================== --- Lib/cookielib.py (revision 51511) +++ Lib/cookielib.py (working copy) @@ -531,7 +531,8 @@ return True if not is_HDN(A): return False - i = A.rfind(B) + try:i = A.rindex(B) + except: i = -1 if i == -1 or i == 0: # A does not have form NB, or N is the empty string return False @@ -595,7 +596,9 @@ """ erhn = req_host = request_host(request) - if req_host.find(".") == -1 and not IPV4_RE.search(req_host): + try: host_delimiter_position = req_host.index(".") + except: host_delimiter_position = -1 + if host_delimiter_position == -1 and not IPV4_RE.search(req_host): erhn = req_host + ".local" return req_host, erhn @@ -616,7 +619,8 @@ def request_port(request): host = request.get_host() - i = host.find(':') + try:i = host.index(':') + except: i = -1 if i >= 0: port = host[i+1:] try: @@ -676,11 +680,13 @@ '.local' """ - i = h.find(".") + try:i = h.index(".") + except: i = -1 if i >= 0: #a = h[:i] # this line is only here to show what a is b = h[i+1:] - i = b.find(".") + try:i = b.index(".") + except: i = -1 if is_HDN(h) and (i >= 0 or b == "local"): return "."+b return h @@ -986,8 +992,10 @@ # XXX This should probably be compared with the Konqueror # (kcookiejar.cpp) and Mozilla implementations, but it's a # losing battle. - i = domain.rfind(".") - j = domain.rfind(".", 0, i) + try:i = domain.rindex(".") + except: i = -1 + try:j = domain.rindex(".", 0, i) + except: j = -1 if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] @@ -1002,7 +1010,8 @@ undotted_domain = domain[1:] else: undotted_domain = domain - embedded_dots = (undotted_domain.find(".") >= 0) + try: embedded_dots = (undotted_domain.index(".") >= 0) + except: embedded_dots = -1 if not embedded_dots and domain != ".local": _debug(" non-local domain %s contains no embedded dot", domain) @@ -1024,7 +1033,9 @@ if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] - if (host_prefix.find(".") >= 0 and + try:host_prefix_dot=host_prefix.index(".") + except: host_prefix_dot = -1 + if (host_prefix_dot >= 0 and not IPV4_RE.search(req_host)): _debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) @@ -1462,7 +1473,8 @@ else: path_specified = False path = request_path(request) - i = path.rfind("/") + try:i = path.rindex("/") + except: i = -1 if i != -1: if version == 0: # Netscape spec parts company from reality here Index: Lib/string.py =================================================================== --- Lib/string.py (revision 51511) +++ Lib/string.py (working copy) @@ -345,32 +345,6 @@ """ return s.count(*args) -# Find substring, return -1 if not found -def find(s, *args): - """find(s, sub [,start [,end]]) -> in - - Return the lowest index in s where substring sub is found, - such that sub is contained within s[start,end]. Optional - arguments start and end are interpreted as in slice notation. - - Return -1 on failure. - - """ - return s.find(*args) - -# Find last substring, return -1 if not found -def rfind(s, *args): - """rfind(s, sub [,start [,end]]) -> int - - Return the highest index in s where substring sub is found, - such that sub is contained within s[start,end]. Optional - arguments start and end are interpreted as in slice notation. - - Return -1 on failure. - - """ - return s.rfind(*args) - # for a bit of speed _float = float _int = int Index: Lib/mimetools.py =================================================================== --- Lib/mimetools.py (revision 51511) +++ Lib/mimetools.py (working copy) @@ -70,7 +70,8 @@ def getparamnames(self): result = [] for p in self.plist: - i = p.find('=') + try:i = p.index('=') + except: i = -1 if i >= 0: result.append(p[:i].lower()) return result Index: Lib/ctypes/macholib/dyld.py =================================================================== --- Lib/ctypes/macholib/dyld.py (revision 51511) +++ Lib/ctypes/macholib/dyld.py (working copy) @@ -150,7 +150,8 @@ return dyld_find(fn, executable_path=executable_path, env=env) except ValueError, e: pass - fmwk_index = fn.rfind('.framework') + try:fmwk_index = fn.rindex('.framework') + except: fmwk_index = -1 if fmwk_index == -1: fmwk_index = len(fn) fn += '.framework' Index: Lib/pyclbr.py =================================================================== --- Lib/pyclbr.py (revision 51511) +++ Lib/pyclbr.py (working copy) @@ -121,7 +121,8 @@ return dict # Check for a dotted module name - i = module.rfind('.') + try:i = module.rindex('.') + except: i = -1 if i >= 0: package = module[:i] submodule = module[i+1:] Index: Lib/robotparser.py =================================================================== --- Lib/robotparser.py (revision 51511) +++ Lib/robotparser.py (working copy) @@ -104,7 +104,8 @@ entry = Entry() state = 0 # remove optional comment and strip line - i = line.find('#') + try:i = line.index('#') + except: i = -1 if i>=0: line = line[:i] line = line.strip() Index: Lib/cgi.py =================================================================== --- Lib/cgi.py (revision 51511) +++ Lib/cgi.py (working copy) @@ -340,7 +340,8 @@ key = plist.pop(0).lower() pdict = {} for p in plist: - i = p.find('=') + try:i = p.index('=') + except: i = -1 if i >= 0: name = p[:i].strip().lower() value = p[i+1:].strip() Index: Lib/pdb.py =================================================================== --- Lib/pdb.py (revision 51511) +++ Lib/pdb.py (working copy) @@ -223,7 +223,8 @@ # split into ';;' separated commands # unless it's an alias command if args[0] != 'alias': - marker = line.find(';;') + try:marker = line.index(';;') + except:marker=-1 if marker >= 0: # queue up everything after marker next = line[marker+2:].lstrip() @@ -310,13 +311,15 @@ filename = None lineno = None cond = None - comma = arg.find(',') + try:comma = arg.index(',') + except: comma = -1 if comma > 0: # parse stuff after comma: "condition" cond = arg[comma+1:].lstrip() arg = arg[:comma].rstrip() # parse stuff before comma: [filename:]lineno | function - colon = arg.rfind(':') + try:colon = arg.rindex(':') + except: colon = -1 funcname = None if colon >= 0: filename = arg[:colon].rstrip() @@ -529,7 +532,8 @@ return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" - i = arg.rfind(':') + try:i = arg.rindex(':') + except:i=-1 filename = arg[:i] arg = arg[i+1:] try: Index: Lib/nntplib.py =================================================================== --- Lib/nntplib.py (revision 51511) +++ Lib/nntplib.py (working copy) @@ -612,7 +612,9 @@ if __name__ == '__main__': import os newshost = 'news' and os.environ["NNTPSERVER"] - if newshost.find('.') == -1: + try:fqdn_separator=newshost.index('.') + except:fqdn_separator=-1 + if fqdn_separator == -1: mode = 'readermode' else: mode = None Index: Lib/pydoc.py =================================================================== --- Lib/pydoc.py (revision 51511) +++ Lib/pydoc.py (working copy) @@ -54,7 +54,7 @@ import sys, imp, os, re, types, inspect, __builtin__, pkgutil from repr import Repr -from string import expandtabs, find, join, lower, split, strip, rfind, rstrip +from string import expandtabs, index, join, lower, split, strip, rindex, rstrip try: from collections import deque except ImportError: @@ -1465,7 +1465,7 @@ desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: - desc += ' in ' + name[:name.rfind('.')] + desc += ' in ' + name[:name.rindex('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if not (inspect.ismodule(object) or @@ -1479,7 +1479,7 @@ object = type(object) desc += ' object' pager(title % desc + '\n\n' + text.document(object, name)) - except (ImportError, ErrorDuringImport), value: + except (ImportError, ErrorDuringImport,ValueError), value: print value def writedoc(thing, forceload=0): @@ -1797,7 +1797,9 @@ def callback(path, modname, desc, modules=modules): if modname and modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' - if find(modname, '.') < 0: + try:module_separator_location=index(modname, '.') + except: module_separator_location = -1 + if module_separator_location < 0: modules[modname] = 1 ModuleScanner().run(callback) self.list(modules.keys()) @@ -1847,7 +1849,7 @@ callback(None, modname, '') else: desc = split(__import__(modname).__doc__ or '', '\n')[0] - if find(lower(modname + ' - ' + desc), key) >= 0: + if index(lower(modname + ' - ' + desc), key) >= 0: callback(None, modname, desc) for importer, modname, ispkg in pkgutil.walk_packages(): @@ -1870,7 +1872,7 @@ module = loader.load_module(modname) desc = (module.__doc__ or '').splitlines()[0] path = getattr(module,'__file__',None) - if find(lower(modname + ' - ' + desc), key) >= 0: + if index(lower(modname + ' - ' + desc), key) >= 0: callback(path, modname, desc) if completer: @@ -2168,7 +2170,9 @@ # -------------------------------------------------- command-line interface def ispath(x): - return isinstance(x, str) and find(x, os.sep) >= 0 + try:i = index(x, os.sep) + except:i=-1 + return isinstance(x, str) and i >= 0 def cli(): """Command-line interface (looks at sys.argv to decide what to do).""" Index: Lib/gettext.py =================================================================== --- Lib/gettext.py (revision 51511) +++ Lib/gettext.py (working copy) @@ -135,21 +135,24 @@ COMPONENT_MODIFIER = 1 << 2 # split up the locale into its base components mask = 0 - pos = locale.find('@') + try:pos = locale.index('@') + except:pos=-1 if pos >= 0: modifier = locale[pos:] locale = locale[:pos] mask |= COMPONENT_MODIFIER else: modifier = '' - pos = locale.find('.') + try:pos = locale.index('.') + except:pos=-1 if pos >= 0: codeset = locale[pos:] locale = locale[:pos] mask |= COMPONENT_CODESET else: codeset = '' - pos = locale.find('_') + try:pos = locale.index('_') + except:pos=-1 if pos >= 0: territory = locale[pos:] locale = locale[:pos] Index: Lib/bsddb/dbtables.py =================================================================== --- Lib/bsddb/dbtables.py (revision 51511) +++ Lib/bsddb/dbtables.py (working copy) @@ -124,14 +124,14 @@ """Verify that the given string does not contain any metadata strings that might interfere with dbtables database operation. """ - if (s.find(_table_names_key) >= 0 or - s.find(_columns) >= 0 or - s.find(_data) >= 0 or - s.find(_rowid) >= 0): - # Then - return 1 - else: - return 0 + + try: + (s.index(_table_names_key) >= 0 or + s.index(_columns) >= 0 or + s.index(_data) >= 0 or + s.index(_rowid) >= 0) + except: return 1 + return 0 class bsdTableDB : Index: Lib/bsddb/dbrecio.py =================================================================== --- Lib/bsddb/dbrecio.py (revision 51511) +++ Lib/bsddb/dbrecio.py (working copy) @@ -86,7 +86,9 @@ if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] - i = string.find(self.buf, '\n', self.pos) + + try:i = string.index(self.buf, '\n', self.pos) + except:i=-1 if i < 0: newpos = self.len else: Index: Lib/urllib.py =================================================================== --- Lib/urllib.py (revision 51511) +++ Lib/urllib.py (working copy) @@ -569,12 +569,12 @@ raise IOError, ('data error', 'bad data URL') if not type: type = 'text/plain;charset=US-ASCII' - semi = type.rfind(';') - if semi >= 0 and '=' not in type[semi:]: - encoding = type[semi+1:] - type = type[:semi] - else: - encoding = '' + try: semi = type.rindex(';') + except: + if '=' not in type[semi:]: + encoding = type[semi+1:] + type = type[:semi] + else: encoding = '' msg = [] msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', time.gmtime(time.time()))) @@ -701,7 +701,10 @@ proxy = self.proxies['http'] urltype, proxyhost = splittype(proxy) proxyhost, proxyselector = splithost(proxyhost) - i = proxyhost.find('@') + 1 + try: + i = proxyhost.index('@') + 1 + except: + i = -1 proxyhost = proxyhost[i:] user, passwd = self.get_user_passwd(proxyhost, realm, i) if not (user or passwd): return None @@ -718,7 +721,10 @@ proxy = self.proxies['https'] urltype, proxyhost = splittype(proxy) proxyhost, proxyselector = splithost(proxyhost) - i = proxyhost.find('@') + 1 + try: + i = proxyhost.index('@') + 1 + except ValueError: + i = -1 proxyhost = proxyhost[i:] user, passwd = self.get_user_passwd(proxyhost, realm, i) if not (user or passwd): return None @@ -731,7 +737,10 @@ def retry_http_basic_auth(self, url, realm, data=None): host, selector = splithost(url) - i = host.find('@') + 1 + try: + i = host.index('@') + 1 + except ValueError: + i = -1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None @@ -744,7 +753,10 @@ def retry_https_basic_auth(self, url, realm, data=None): host, selector = splithost(url) - i = host.find('@') + 1 + try: + i = host.index('@') + 1 + except ValueError: + i = -1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None Index: Lib/rfc822.py =================================================================== --- Lib/rfc822.py (revision 51511) +++ Lib/rfc822.py (working copy) @@ -197,7 +197,8 @@ You may override this method in order to use Message parsing on tagged data in RFC 2822-like formats with special header formats. """ - i = line.find(':') + try:i = line.index(':') + except: i =-1 if i > 0: return line[:i].lower() return None @@ -307,7 +308,7 @@ else: if have_header: result.append(current) - current = s[s.find(":") + 1:].strip() + current = s[s.index(":") + 1:].strip() have_header = 1 if have_header: result.append(current) @@ -340,7 +341,8 @@ else: if raw: raw.append(', ') - i = h.find(':') + try:i = h.index(':') + except: i = -1 if i > 0: addr = h[i+1:] raw.append(addr) @@ -856,7 +858,8 @@ data = stuff + data[1:] if len(data) == 4: s = data[3] - i = s.find('+') + try:i = s.index('+') + except:i=-1 if i > 0: data[3:] = [s[:i], s[i+1:]] else: @@ -874,7 +877,8 @@ if mm > 12: mm = mm - 12 if dd[-1] == ',': dd = dd[:-1] - i = yy.find(':') + try:i = yy.index(':') + except:i=-1 if i > 0: yy, tm = tm, yy if yy[-1] == ',': Index: Lib/telnetlib.py =================================================================== --- Lib/telnetlib.py (revision 51511) +++ Lib/telnetlib.py (working copy) @@ -301,7 +301,8 @@ """ n = len(match) self.process_rawq() - i = self.cookedq.find(match) + try: i = self.cookedq.index(match) + except ValueError: i = -1 if i >= 0: i = i+n buf = self.cookedq[:i] @@ -317,7 +318,8 @@ i = max(0, len(self.cookedq)-n) self.fill_rawq() self.process_rawq() - i = self.cookedq.find(match, i) + try: i = self.cookedq.index(match, i) + except: i = -1 if i >= 0: i = i+n buf = self.cookedq[:i] Index: Lib/tarfile.py =================================================================== --- Lib/tarfile.py (revision 51511) +++ Lib/tarfile.py (working copy) @@ -655,7 +655,8 @@ if size < 0: size = sys.maxint - nl = self.linebuffer.find("\n") + try:nl = self.linebuffer.index("\n") + except:nl=-1 if nl >= 0: nl = min(nl, size) else: @@ -666,7 +667,8 @@ break self.linebuffer += buf size -= len(buf) - nl = self.linebuffer.find("\n") + try:nl = self.linebuffer.index("\n") + except: nl=-1 if nl == -1: s = self.linebuffer self.linebuffer = "" Index: Lib/lib-tk/Tkinter.py =================================================================== --- Lib/lib-tk/Tkinter.py (revision 51511) +++ Lib/lib-tk/Tkinter.py (working copy) @@ -1065,7 +1065,8 @@ w = w._root() name = name[1:] while name: - i = name.find('.') + try:i = name.index('.') + except: i = -1 if i >= 0: name, tail = name[:i], name[i+1:] else: Index: Lib/mhlib.py =================================================================== --- Lib/mhlib.py (revision 51511) +++ Lib/mhlib.py (working copy) @@ -356,7 +356,8 @@ if seq == 'all': return all # Test for X:Y before X-Y because 'seq:-n' matches both - i = seq.find(':') + try:i = seq.index(':') + except: i = -1 if i >= 0: head, dir, tail = seq[:i], '', seq[i+1:] if tail[:1] in '-+': @@ -394,7 +395,8 @@ i = bisect(all, anchor-1) return all[i:i+count] # Test for X-Y next - i = seq.find('-') + try:i = seq.index('-') + except:i=-1 if i >= 0: begin = self._parseindex(seq[:i], all) end = self._parseindex(seq[i+1:], all) @@ -682,7 +684,8 @@ hit = 0 for line in self.headers: if not line[0].isspace(): - i = line.find(':') + try:i = line.index(':') + except: i = -1 if i > 0: hit = pred(line[:i].lower()) if hit: headers.append(line) Index: Lib/mailbox.py =================================================================== --- Lib/mailbox.py (revision 51511) +++ Lib/mailbox.py (working copy) @@ -653,7 +653,8 @@ """Format a message and blindly write to self._file.""" from_line = None if isinstance(message, str) and message.startswith('From '): - newline = message.find('\n') + try: newline = message.index('\n') + except:newline=-1 if newline != -1: from_line = message[:newline] message = message[newline + 1:] @@ -1252,7 +1253,8 @@ break self._file.write(buffer.replace('\n', os.linesep)) elif isinstance(message, str): - body_start = message.find('\n\n') + 2 + try:body_start = message.index('\n\n') + 2 + except:body_start=-1 if body_start - 2 != -1: self._file.write(message[:body_start].replace('\n', os.linesep)) Index: Lib/StringIO.py =================================================================== --- Lib/StringIO.py (revision 51511) +++ Lib/StringIO.py (working copy) @@ -153,7 +153,7 @@ if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [] - i = self.buf.find('\n', self.pos) + try:i = self.buf.index('\n', self.pos) if i < 0: newpos = self.len else: Index: Lib/email/_parseaddr.py =================================================================== --- Lib/email/_parseaddr.py (revision 51511) +++ Lib/email/_parseaddr.py (working copy) @@ -54,7 +54,8 @@ # There's a dayname here. Skip it del data[0] else: - i = data[0].rfind(',') + try:i = data[0].rindex(',') + except: i = -1 if i >= 0: data[0] = data[0][i+1:] if len(data) == 3: # RFC 850 date, deprecated @@ -63,7 +64,8 @@ data = stuff + data[1:] if len(data) == 4: s = data[3] - i = s.find('+') + try:i = s.index('+') + except: i = -1 if i > 0: data[3:] = [s[:i], s[i+1:]] else: @@ -82,7 +84,8 @@ mm -= 12 if dd[-1] == ',': dd = dd[:-1] - i = yy.find(':') + try:i = yy.index(':') + except: i = -1 if i > 0: yy, tm = tm, yy if yy[-1] == ',': Index: Lib/email/feedparser.py =================================================================== --- Lib/email/feedparser.py (revision 51511) +++ Lib/email/feedparser.py (working copy) @@ -467,7 +467,8 @@ self._cur.defects.append(defect) continue # Split the line on the colon separating field name from value. - i = line.find(':') + try:i = line.index(':') + except: i = -1 if i < 0: defect = errors.MalformedHeaderDefect(line) self._cur.defects.append(defect) Index: Lib/zipfile.py =================================================================== --- Lib/zipfile.py (revision 51511) +++ Lib/zipfile.py (working copy) @@ -149,8 +149,8 @@ END_BLOCK = min(filesize, 1024 * 4) fpin.seek(filesize - END_BLOCK, 0) data = fpin.read() - start = data.rfind(stringEndArchive) - if start >= 0: # Correct signature string was found + try: + start = data.rindex(stringEndArchive) endrec = struct.unpack(structEndArchive, data[start:start+22]) endrec = list(endrec) comment = data[start+22:] @@ -161,7 +161,7 @@ if endrec[-4] == -1 or endrec[-4] == 0xffffffff: return _EndRecData64(fpin, - END_BLOCK + start, endrec) return endrec - return # Error, return None + except: return # Error, return None class ZipInfo (object): @@ -193,8 +193,9 @@ # Terminate the file name at the first null byte. Null bytes in file # names are used as tricks by viruses in archives. - null_byte = filename.find(chr(0)) - if null_byte >= 0: + try: + null_byte = filename.index(chr(0)) + except: filename = filename[0:null_byte] # This is used to ensure paths in generated ZIP files always use # forward slashes as the directory separator, as required by the Index: Lib/httplib.py =================================================================== --- Lib/httplib.py (revision 51511) +++ Lib/httplib.py (working copy) @@ -542,7 +542,8 @@ while True: if chunk_left is None: line = self.fp.readline() - i = line.find(';') + try:i = line.index(';') + except:i=-1 if i >= 0: line = line[:i] # strip chunk-extensions chunk_left = int(line, 16) @@ -638,8 +639,10 @@ def _set_hostport(self, host, port): if port is None: - i = host.rfind(':') - j = host.rfind(']') # ipv6 addresses have [...] + try:i = host.rindex(':') + except: i = -1 + try:j = host.rindex(']') # ipv6 addresses have [...] + except: j = -1 if i > j: try: port = int(host[i+1:]) @@ -1037,7 +1040,8 @@ L = [self._buf] self._buf = '' while 1: - i = L[-1].find("\n") + try:i = L[-1].index("\n") + except:i=-1 if i >= 0: break s = self._read() @@ -1050,7 +1054,8 @@ else: all = "".join(L) # XXX could do enough bookkeeping not to do a 2nd search - i = all.find("\n") + 1 + try:i = all.index("\n") + 1 + except:i=-1 line = all[:i] self._buf = all[i:] return line Index: Lib/urllib2.py =================================================================== --- Lib/urllib2.py (revision 51511) +++ Lib/urllib2.py (working copy) @@ -301,12 +301,12 @@ # oops, coincidental match continue - i = meth.find("_") + i = meth.index("_") protocol = meth[:i] condition = meth[i+1:] if condition.startswith("error"): - j = condition.find("_") + i + 1 + j = condition.index("_") + i + 1 kind = meth[j+1:] try: kind = int(kind) @@ -642,7 +642,9 @@ raise ValueError("proxy URL with no authority: %r" % proxy) # We have an authority, so for RFC 3986-compliant URLs (by ss 3. # and 3.3.), path is empty or starts with '/' - end = r_scheme.find("/", 2) + try: + end = r_scheme.index("/", 2) + except: end = -1 if end == -1: end = None authority = r_scheme[2:end] Index: Lib/ConfigParser.py =================================================================== --- Lib/ConfigParser.py (revision 51511) +++ Lib/ConfigParser.py (working copy) @@ -468,7 +468,8 @@ if vi in ('=', ':') and ';' in optval: # ';' is a comment delimiter only if it follows # a spacing character - pos = optval.find(';') + try:pos = optval.index(';') + except:pos=-1 if pos != -1 and optval[pos-1].isspace(): optval = optval[:pos] optval = optval.strip() @@ -599,7 +600,8 @@ if depth > MAX_INTERPOLATION_DEPTH: raise InterpolationDepthError(option, section, rest) while rest: - p = rest.find("%") + try:p = rest.index("%") + except: p = -1 if p < 0: accum.append(rest) return Index: Lib/test/test_repr.py =================================================================== --- Lib/test/test_repr.py (revision 51511) +++ Lib/test/test_repr.py (working copy) @@ -112,7 +112,9 @@ s = r(ClassWithFailingRepr) self.failUnless(s.startswith("")) - self.failUnless(s.find("...") in [12, 13]) + try: pos = s.index("...") + except ValueError: pos = -1 + self.failUnless(pos in [12, 13]) def test_file(self): fp = open(unittest.__file__) Index: Lib/test/test_traceback.py =================================================================== --- Lib/test/test_traceback.py (revision 51511) +++ Lib/test/test_traceback.py (working copy) @@ -33,7 +33,11 @@ self.assert_(len(err) == 4) self.assert_(err[1].strip() == "return x!") self.assert_("^" in err[2]) # third line has caret - self.assert_(err[1].find("!") == err[2].find("^")) # in the right place + try: e1=err[1].index('!') + except: e1= -1 + try: e2 = err[2].index('^') + except: e2 = -1 + self.assert_(e1 == e2)# in the right place def test_nocaret(self): if is_jython: @@ -50,7 +54,11 @@ self.assert_(len(err) == 4) self.assert_(err[1].strip() == "print 2") self.assert_("^" in err[2]) - self.assert_(err[1].find("2") == err[2].find("^")) + try: e1=err[1].index('2') + except: e1 = -1 + try: e2=err[2].index('^') + except: e2 = -1 + self.assert_(e1 == e2) def test_bug737473(self): import sys, os, tempfile, time Index: Lib/test/test_descr.py =================================================================== --- Lib/test/test_descr.py (revision 51511) +++ Lib/test/test_descr.py (working copy) @@ -1648,7 +1648,9 @@ verify(not c1 == c2) # Note that the module name appears in str/repr, and that varies # depending on whether this test is run standalone or from a framework. - verify(str(c1).find('C object at ') >= 0) + try:c_pos = str(c1).index('C object at ') + except: c_pos = -1 + verify(c_pos>= 0) vereq(str(c1), repr(c1)) verify(-1 not in c1) for i in range(10): @@ -1672,7 +1674,9 @@ verify(not d1 == d2) # Note that the module name appears in str/repr, and that varies # depending on whether this test is run standalone or from a framework. - verify(str(d1).find('D object at ') >= 0) + try: d_pos = str(d1).index('D object at ') + except: d_pos = -1 + verify(d_pos >= 0) vereq(str(d1), repr(d1)) verify(-1 not in d1) for i in range(10): @@ -1814,7 +1818,9 @@ try: weakref.ref(no) except TypeError, msg: - verify(str(msg).find("weak reference") >= 0) + try:weakref_pos = str(msg).index('weak reference') + except:weakref_pos = -1 + verify(weakref_pos>= 0) else: verify(0, "weakref.ref(no) should be illegal") class Weak(object): @@ -1867,7 +1873,9 @@ try: setattr(raw, attr, 42) except TypeError, msg: - if str(msg).find('readonly') < 0: + try: readonly_pos = str(msg).index('readonly') + except: readonly_pos = -1 + if readonly_pos < 0: raise TestFailed("when setting readonly attr %r on a " "property, got unexpected TypeError " "msg %r" % (attr, str(msg))) @@ -2410,7 +2418,9 @@ try: sandbox.r_exec(code) except IOError, msg: - if str(msg).find("restricted") >= 0: + try: pos = str(msg).index("restricted") + except ValueError: pos = -1 + if pos >= 0: outcome = "OK" else: outcome = "got an exception, but not an expected one" Index: Lib/test/test_unicode.py =================================================================== --- Lib/test/test_unicode.py (revision 51511) +++ Lib/test/test_unicode.py (working copy) @@ -113,22 +113,6 @@ self.checkequalnofix(3, u'aaa', 'count', 'a', -10) self.checkequalnofix(2, u'aaa', 'count', 'a', 0, -1) self.checkequalnofix(0, u'aaa', 'count', 'a', 0, -10) - - def test_find(self): - self.checkequalnofix(0, u'abcdefghiabc', 'find', u'abc') - self.checkequalnofix(9, u'abcdefghiabc', 'find', u'abc', 1) - self.checkequalnofix(-1, u'abcdefghiabc', 'find', u'def', 4) - - self.assertRaises(TypeError, u'hello'.find) - self.assertRaises(TypeError, u'hello'.find, 42) - - def test_rfind(self): - string_tests.CommonTest.test_rfind(self) - # check mixed argument types - self.checkequalnofix(9, 'abcdefghiabc', 'rfind', u'abc') - self.checkequalnofix(12, 'abcdefghiabc', 'rfind', u'') - self.checkequalnofix(12, u'abcdefghiabc', 'rfind', '') - def test_index(self): string_tests.CommonTest.test_index(self) # check mixed argument types Index: Lib/test/test_socket.py =================================================================== --- Lib/test/test_socket.py (revision 51511) +++ Lib/test/test_socket.py (working copy) @@ -102,7 +102,9 @@ # Do some munging to start the client test. methodname = self.id() - i = methodname.rfind('.') + try: + i = methodname.rindex('.') + except ValueError: i = -1 methodname = methodname[i+1:] test_method = getattr(self, '_' + methodname) self.client_thread = thread.start_new_thread( @@ -265,7 +267,9 @@ except socket.error: # Probably name lookup wasn't set up right; skip this test return - self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") + try: pos = ip.index('.') + except ValueError: pos = -1 + self.assert_( pos >= 0, "Error resolving host to ip.") try: hname, aliases, ipaddrs = socket.gethostbyaddr(ip) except socket.error: Index: Lib/test/test_file.py =================================================================== --- Lib/test/test_file.py (revision 51511) +++ Lib/test/test_file.py (working copy) @@ -162,7 +162,12 @@ except ValueError, msg: if msg[0] != 0: s = str(msg) - if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: + + try: filename_location = s.index(TESTFN) + except: filename_location = -1 + try: mode_location = s.index(bad_mode) + except: mode_location = -1 + if filename_location != -1 or mode_location == -1: self.fail("bad error message for invalid mode: %s" % s) # if msg[0] == 0, we're probably on Windows where there may be # no obvious way to discover why open() failed. Index: Lib/test/test_mmap.py =================================================================== --- Lib/test/test_mmap.py (revision 51511) +++ Lib/test/test_mmap.py (working copy) @@ -24,8 +24,9 @@ # Simple sanity checks print type(m) # SF bug 128713: segfaulted on Linux - print ' Position of foo:', m.find('foo') / float(PAGESIZE), 'pages' - vereq(m.find('foo'), PAGESIZE) + position = m.index('foo') + print ' Position of foo:', position / float(PAGESIZE), 'pages' + vereq(position, PAGESIZE) print ' Length of file:', len(m) / float(PAGESIZE), 'pages' vereq(len(m), 2*PAGESIZE) @@ -289,7 +290,7 @@ else: verify(0, 'expected a mmap.error but did not get it') - # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, + # Do a tougher .index() test. SF bug 515943 pointed out that, in 2.2, # searching for data with embedded \0 bytes didn't work. f = open(TESTFN, 'w+') @@ -304,8 +305,17 @@ for start in range(n+1): for finish in range(start, n+1): slice = data[start : finish] - vereq(m.find(slice), data.find(slice)) - vereq(m.find(slice + 'x'), -1) + try: + r1= m.index(slice) + except ValueError: r1 = -1 + try: + r2 = data.index(slice) + except ValueError: r2 = -1 + vereq(r1, r2) + try: + r3 = m.index(slice+'x') + except ValueError: r3 = -1 + vereq(r3, -1) m.close() finally: Index: Lib/test/test_minidom.py =================================================================== --- Lib/test/test_minidom.py (revision 51511) +++ Lib/test/test_minidom.py (working copy) @@ -400,7 +400,9 @@ string1 = repr(el) string2 = str(el) confirm(string1 == string2) - confirm(string1.find("slash:abc") != -1) + try: i=string1.index("slash:abc") + except: i = -1 + confirm(i != -1) dom.unlink() def testAttributeRepr(): Index: Lib/test/test_strptime.py =================================================================== --- Lib/test/test_strptime.py (revision 51511) +++ Lib/test/test_strptime.py (working copy) @@ -119,13 +119,19 @@ def test_pattern(self): # Test TimeRE.pattern pattern_string = self.time_re.pattern(r"%a %A %d") - self.failUnless(pattern_string.find(self.locale_time.a_weekday[2]) != -1, + try: res = pattern_string.index(self.locale_time.a_weekday[2]) + except: res = -1 + self.failUnless(res != -1, "did not find abbreviated weekday in pattern string '%s'" % pattern_string) - self.failUnless(pattern_string.find(self.locale_time.f_weekday[4]) != -1, + try: res = pattern_string.index(self.locale_time.f_weekday[4]) + except: res = -1 + self.failUnless(res != -1, "did not find full weekday in pattern string '%s'" % pattern_string) - self.failUnless(pattern_string.find(self.time_re['d']) != -1, + try: res=pattern_string.index(self.time_re['d']) + except: res = -1 + self.failUnless(res != -1, "did not find 'd' directive pattern string '%s'" % pattern_string) Index: Lib/test/test_wsgiref.py =================================================================== --- Lib/test/test_wsgiref.py (revision 51511) +++ Lib/test/test_wsgiref.py (working copy) @@ -515,7 +515,10 @@ "Content-Length: %d\r\n" "\r\n%s" % (h.error_status,len(h.error_body),h.error_body)) - self.failUnless(h.stderr.getvalue().find("AssertionError")<>-1) + try: + error_location = h.stderr.getvalue().index("AssertionError") + except ValueError: error_location = -1 + self.failUnless(error_location <> -1) def testErrorAfterOutput(self): MSG = "Some output has been sent" @@ -528,7 +531,10 @@ self.assertEqual(h.stdout.getvalue(), "Status: 200 OK\r\n" "\r\n"+MSG) - self.failUnless(h.stderr.getvalue().find("AssertionError")<>-1) + try: + error_location = h.stderr.getvalue().index("AssertionError") + except: error_location = -1 + self.failUnless(error_location <> -1) def testHeaderFormats(self): Index: Lib/test/test_decimal.py =================================================================== --- Lib/test/test_decimal.py (revision 51511) +++ Lib/test/test_decimal.py (working copy) @@ -152,14 +152,17 @@ return def eval_line(self, s): - if s.find(' -> ') >= 0 and s[:2] != '--' and not s.startswith(' --'): + try: arrow_location = s.index(' -> ') + except: arrow_location = -1 + if arrow_location >= 0 and s[:2] != '--' and not s.startswith(' --'): s = (s.split('->')[0] + '->' + s.split('->')[1].split('--')[0]).strip() else: s = s.split('--')[0].strip() for ignore in self.ignore_list: - if s.find(ignore) >= 0: + try: ignore_location = s.index(ignore) + if ignore_location >= 0: #print s.split()[0], 'NotImplemented--', ignore return if not s: Index: Lib/test/test_strop.py =================================================================== --- Lib/test/test_strop.py (revision 51511) +++ Lib/test/test_strop.py (working copy) @@ -28,14 +28,6 @@ self.assert_(strop.capitalize(" hello ") == " hello ") self.assert_(strop.capitalize("hello ") == "Hello ") - def test_find(self): - self.assert_(strop.find("abcdefghiabc", "abc") == 0) - self.assert_(strop.find("abcdefghiabc", "abc", 1) == 9) - self.assert_(strop.find("abcdefghiabc", "def", 4) == -1) - - def test_rfind(self): - self.assert_(strop.rfind("abcdefghiabc", "abc") == 9) - def test_lower(self): self.assert_(strop.lower("HeLLo") == "hello") Index: Lib/test/test_subprocess.py =================================================================== --- Lib/test/test_subprocess.py (revision 51511) +++ Lib/test/test_subprocess.py (working copy) @@ -472,7 +472,9 @@ except OSError, e: # The attribute child_traceback should contain "os.chdir" # somewhere. - self.assertNotEqual(e.child_traceback.find("os.chdir"), -1) + try:location_of_os_chdir = e.child_traceback.index("os.chdir") + except: location_of_os_chdir = -1 + self.assertNotEqual(location_of_os_chdir, -1) else: self.fail("Expected OSError") @@ -618,7 +620,9 @@ p = subprocess.Popen(["set"], shell=1, stdout=subprocess.PIPE, env=newenv) - self.assertNotEqual(p.stdout.read().find("physalis"), -1) + try: ps = p.stdout.read().index('physalis') + except ValueError: ps = -1 + self.assertNotEqual(ps, -1) def test_shell_string(self): # Run command through the shell (string) @@ -627,7 +631,9 @@ p = subprocess.Popen("set", shell=1, stdout=subprocess.PIPE, env=newenv) - self.assertNotEqual(p.stdout.read().find("physalis"), -1) + try: ps = p.stdout.read().index('physalis') + except ValueError: ps = -1 + self.assertNotEqual(ps, -1) def test_call_string(self): # call() function with string argument on Windows Index: Lib/test/string_tests.py =================================================================== --- Lib/test/string_tests.py (revision 51511) +++ Lib/test/string_tests.py (working copy) @@ -150,56 +150,6 @@ self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i)) self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i)) - def test_find(self): - self.checkequal(0, 'abcdefghiabc', 'find', 'abc') - self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1) - self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4) - - self.checkequal(0, 'abc', 'find', '', 0) - self.checkequal(3, 'abc', 'find', '', 3) - self.checkequal(-1, 'abc', 'find', '', 4) - - self.checkraises(TypeError, 'hello', 'find') - self.checkraises(TypeError, 'hello', 'find', 42) - - # For a variety of combinations, - # verify that str.find() matches __contains__ - # and that the found substring is really at that location - charset = ['', 'a', 'b', 'c'] - digits = 5 - base = len(charset) - teststrings = set() - for i in xrange(base ** digits): - entry = [] - for j in xrange(digits): - i, m = divmod(i, base) - entry.append(charset[m]) - teststrings.add(''.join(entry)) - teststrings = list(teststrings) - for i in teststrings: - i = self.fixtype(i) - for j in teststrings: - loc = i.find(j) - r1 = (loc != -1) - r2 = j in i - if r1 != r2: - self.assertEqual(r1, r2) - if loc != -1: - self.assertEqual(i[loc:loc+len(j)], j) - - def test_rfind(self): - self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc') - self.checkequal(12, 'abcdefghiabc', 'rfind', '') - self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd') - self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz') - - self.checkequal(3, 'abc', 'rfind', '', 0) - self.checkequal(3, 'abc', 'rfind', '', 3) - self.checkequal(-1, 'abc', 'rfind', '', 4) - - self.checkraises(TypeError, 'hello', 'rfind') - self.checkraises(TypeError, 'hello', 'rfind', 42) - def test_index(self): self.checkequal(0, 'abcdefghiabc', 'index', '') self.checkequal(3, 'abcdefghiabc', 'index', 'def') Index: Lib/test/test_bigmem.py =================================================================== --- Lib/test/test_bigmem.py (revision 51511) +++ Lib/test/test_bigmem.py (working copy) @@ -97,22 +97,6 @@ self.assertEquals(len(s.strip(' ')), 0) @bigmemtest(minsize=_2G, memuse=2) - def test_find(self, size): - SUBSTR = ' abc def ghi' - sublen = len(SUBSTR) - s = ''.join([SUBSTR, '-' * size, SUBSTR]) - self.assertEquals(s.find(' '), 0) - self.assertEquals(s.find(SUBSTR), 0) - self.assertEquals(s.find(' ', sublen), sublen + size) - self.assertEquals(s.find(SUBSTR, len(SUBSTR)), sublen + size) - self.assertEquals(s.find('i'), SUBSTR.find('i')) - self.assertEquals(s.find('i', sublen), - sublen + size + SUBSTR.find('i')) - self.assertEquals(s.find('i', size), - sublen + size + SUBSTR.find('i')) - self.assertEquals(s.find('j'), -1) - - @bigmemtest(minsize=_2G, memuse=2) def test_index(self, size): SUBSTR = ' abc def ghi' sublen = len(SUBSTR) @@ -238,21 +222,6 @@ self.assertEquals(s[-10:], ' aaaa') @bigmemtest(minsize=_2G, memuse=2) - def test_rfind(self, size): - SUBSTR = ' abc def ghi' - sublen = len(SUBSTR) - s = ''.join([SUBSTR, '-' * size, SUBSTR]) - self.assertEquals(s.rfind(' '), sublen + size + SUBSTR.rfind(' ')) - self.assertEquals(s.rfind(SUBSTR), sublen + size) - self.assertEquals(s.rfind(' ', 0, size), SUBSTR.rfind(' ')) - self.assertEquals(s.rfind(SUBSTR, 0, sublen + size), 0) - self.assertEquals(s.rfind('i'), sublen + size + SUBSTR.rfind('i')) - self.assertEquals(s.rfind('i', 0, sublen), SUBSTR.rfind('i')) - self.assertEquals(s.rfind('i', 0, sublen + size), - SUBSTR.rfind('i')) - self.assertEquals(s.rfind('j'), -1) - - @bigmemtest(minsize=_2G, memuse=2) def test_rindex(self, size): SUBSTR = ' abc def ghi' sublen = len(SUBSTR) Index: Lib/test/test_urllib2.py =================================================================== --- Lib/test/test_urllib2.py (revision 51511) +++ Lib/test/test_urllib2.py (working copy) @@ -284,7 +284,7 @@ elif action == "return request": return Request("http://blah/") elif action.startswith("error"): - code = action[action.rfind(" ")+1:] + code = action[action.rindex(" ")+1:] try: code = int(code) except ValueError: Index: Lib/urlparse.py =================================================================== --- Lib/urlparse.py (revision 51511) +++ Lib/urlparse.py (working copy) @@ -161,16 +161,26 @@ def _splitparams(url): if '/' in url: - i = url.find(';', url.rfind('/')) + try: + slash_position = url.rindex('/') + except ValueError: + slash_position = -1 + i = url.index(';', slash_position) if i < 0: return url, '' else: - i = url.find(';') + try: + i = url.index(';') + except ValueError: + i = -1 return url[:i], url[i+1:] def _splitnetloc(url, start=0): for c in '/?#': # the order is important! - delim = url.find(c, start) + try: + delim = url.index(c, start) + except IndexError: + delim = -1 if delim >= 0: break else: @@ -191,7 +201,8 @@ if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() netloc = query = fragment = '' - i = url.find(':') + try: i = url.index(':') + except ValueError: i = -1 if i > 0: if url[:i] == 'http': # optimize the common case scheme = url[:i].lower() Index: Lib/locale.py =================================================================== --- Lib/locale.py (revision 51511) +++ Lib/locale.py (working copy) @@ -101,7 +101,8 @@ seps = 0 spaces = "" if s[-1] == ' ': - sp = s.find(' ') + try: sp = s.index(' ') + except: sp=-1 spaces = s[sp:] s = s[:sp] while s and grouping: @@ -153,7 +154,8 @@ or 'decimal_point'] formatted = decimal_point.join(parts) while seps: - sp = formatted.find(' ') + try:sp = formatted.index(' ') + except: sp = -1 if sp == -1: break formatted = formatted[:sp] + formatted[sp+1:] seps -= 1 Index: Lib/xml/dom/minidom.py =================================================================== --- Lib/xml/dom/minidom.py (revision 51511) +++ Lib/xml/dom/minidom.py (working copy) @@ -1143,7 +1143,9 @@ nodeName = "#cdata-section" def writexml(self, writer, indent="", addindent="", newl=""): - if self.data.find("]]>") >= 0: + try: cdata_index = self.data.index("]]>") + except: cdata_index=-1 + if cdata_index >= 0: raise ValueError("']]>' not allowed in a CDATA section") writer.write("" % self.data) Index: Lib/HTMLParser.py =================================================================== --- Lib/HTMLParser.py (revision 51511) +++ Lib/HTMLParser.py (working copy) @@ -255,8 +255,10 @@ lineno, offset = self.getpos() if "\n" in self.__starttag_text: lineno = lineno + self.__starttag_text.count("\n") + try:line_terminator_position = self.__starttag_text.rindex("\n") + except:line_terminator_position = -1 offset = len(self.__starttag_text) \ - - self.__starttag_text.rfind("\n") + - line_terminator_position else: offset = offset + len(self.__starttag_text) self.error("junk characters in start tag: %r" Index: Lib/imputil.py =================================================================== --- Lib/imputil.py (revision 51511) +++ Lib/imputil.py (working copy) @@ -169,7 +169,8 @@ assert globals is parent.__dict__ return parent - i = parent_fqname.rfind('.') + try:i = parent_fqname.rindex('.') + except:i=-1 # a module outside of a package has no particular import context if i == -1: