From 9d72bb452bced3a100f07f8a9e30c4495a9ec41a Mon Sep 17 00:00:00 2001 From: Neal Norwitz Date: Tue, 17 Apr 2007 08:48:32 +0000 Subject: [PATCH] Remove functions in string module that are also string methods. Also remove: * all calls to functions in the string module (except maketrans) * everything from stropmodule except for maketrans() which is still used --- Lib/Cookie.py | 11 +- Lib/SimpleXMLRPCServer.py | 11 +- Lib/bsddb/dbrecio.py | 7 +- Lib/bsddb/test/test_associate.py | 12 +- Lib/bsddb/test/test_compat.py | 4 +- Lib/bsddb/test/test_dbobj.py | 4 +- Lib/bsddb/test/test_join.py | 2 +- Lib/bsddb/test/test_lock.py | 2 +- Lib/bsddb/test/test_pickle.py | 2 +- Lib/distutils/cmd.py | 6 +- Lib/distutils/command/bdist.py | 2 +- Lib/distutils/command/bdist_msi.py | 2 +- Lib/distutils/command/bdist_rpm.py | 18 +- Lib/distutils/command/bdist_wininst.py | 10 +- Lib/distutils/command/build_clib.py | 5 +- Lib/distutils/command/build_ext.py | 24 +- Lib/distutils/command/build_py.py | 14 +- Lib/distutils/command/config.py | 10 +- Lib/distutils/command/install.py | 12 +- Lib/distutils/command/install_lib.py | 2 +- Lib/distutils/command/register.py | 4 +- Lib/distutils/command/sdist.py | 6 +- Lib/distutils/cygwinccompiler.py | 5 +- Lib/distutils/dist.py | 24 +- Lib/distutils/emxccompiler.py | 5 +- Lib/distutils/extension.py | 6 +- Lib/distutils/fancy_getopt.py | 14 +- Lib/distutils/filelist.py | 16 +- Lib/distutils/msvccompiler.py | 22 +- Lib/distutils/mwerkscompiler.py | 6 +- Lib/distutils/spawn.py | 12 +- Lib/distutils/sysconfig.py | 7 +- Lib/distutils/text_file.py | 22 +- Lib/distutils/util.py | 26 +- Lib/distutils/version.py | 17 +- Lib/idlelib/Debugger.py | 3 +- Lib/idlelib/MultiCall.py | 3 +- Lib/idlelib/aboutDialog.py | 4 +- Lib/idlelib/configDialog.py | 8 +- Lib/idlelib/configHandler.py | 3 +- Lib/idlelib/keybindingDialog.py | 2 +- Lib/inspect.py | 44 +- Lib/logging/__init__.py | 12 +- Lib/logging/config.py | 24 +- Lib/logging/handlers.py | 12 +- Lib/plat-irix6/cddb.py | 9 +- Lib/plat-irix6/cdplayer.py | 7 +- Lib/plat-mac/EasyDialogs.py | 7 +- Lib/plat-mac/aepack.py | 2 - Lib/plat-mac/aetypes.py | 15 +- Lib/plat-mac/buildtools.py | 5 +- Lib/plat-mac/gensuitemodule.py | 4 +- Lib/plat-mac/ic.py | 5 +- Lib/plat-riscos/riscospath.py | 16 +- Lib/plat-riscos/rourl2path.py | 2 +- Lib/platform.py | 60 +- Lib/pydoc.py | 125 +-- Lib/string.py | 324 +------ Lib/test/test_future2.py | 2 +- Lib/test/test_logging.py | 7 +- Lib/test/test_scope.py | 22 +- Lib/test/test_string.py | 89 +- Lib/test/test_strop.py | 110 --- Lib/test/test_sundry.py | 1 - Lib/test/test_unicode.py | 2 +- Lib/urllib.py | 2 +- Lib/xml/etree/ElementTree.py | 32 +- Misc/NEWS | 8 + Modules/stropmodule.c | 1186 +----------------------- 69 files changed, 396 insertions(+), 2113 deletions(-) diff --git a/Lib/Cookie.py b/Lib/Cookie.py index 368a3bb5bd0..4a34ff46ac1 100644 --- a/Lib/Cookie.py +++ b/Lib/Cookie.py @@ -307,15 +307,14 @@ _Translator = { _idmap = ''.join(chr(x) for x in xrange(256)) -def _quote(str, LegalChars=_LegalChars, - idmap=_idmap, translate=string.translate): +def _quote(str, LegalChars=_LegalChars, idmap=_idmap): # # If the string does not need to be double-quoted, # then just return the string. Otherwise, surround # the string in doublequotes and precede quote (with a \) # special characters. # - if "" == translate(str, idmap, LegalChars): + if "" == str.translate(idmap, LegalChars): return str else: return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"' @@ -440,14 +439,12 @@ class Morsel(dict): return K.lower() in self._reserved # end isReservedKey - def set(self, key, val, coded_val, - LegalChars=_LegalChars, - idmap=_idmap, translate=string.translate): + def set(self, key, val, coded_val, LegalChars=_LegalChars, idmap=_idmap): # First we verify that the key isn't a reserved word # Second we make sure it only contains legal characters if key.lower() in self._reserved: raise CookieError("Attempt to set a reserved key: %s" % key) - if "" != translate(key, idmap, LegalChars): + if "" != key.translate(idmap, LegalChars): raise CookieError("Illegal key value: %s" % key) # It's a good key, so save it. diff --git a/Lib/SimpleXMLRPCServer.py b/Lib/SimpleXMLRPCServer.py index 814ede10254..7065cc0a4f9 100644 --- a/Lib/SimpleXMLRPCServer.py +++ b/Lib/SimpleXMLRPCServer.py @@ -21,15 +21,14 @@ server.serve_forever() class MyFuncs: def __init__(self): - # make all of the string functions available through - # string.func_name - import string - self.string = string + # make all of the sys functions available through sys.func_name + import sys + self.sys = sys def _listMethods(self): # implement this method so that system.listMethods - # knows to advertise the strings methods + # knows to advertise the sys methods return list_public_methods(self) + \ - ['string.' + method for method in list_public_methods(self.string)] + ['sys.' + method for method in list_public_methods(self.sys)] def pow(self, x, y): return pow(x, y) def add(self, x, y) : return x + y diff --git a/Lib/bsddb/dbrecio.py b/Lib/bsddb/dbrecio.py index 975a2d9c0a4..cb2725cfe04 100644 --- a/Lib/bsddb/dbrecio.py +++ b/Lib/bsddb/dbrecio.py @@ -29,7 +29,6 @@ From: """ import errno -import string class DBRecIO: def __init__(self, db, key, txn=None): @@ -83,9 +82,9 @@ class DBRecIO: if self.closed: raise ValueError, "I/O operation on closed file" if self.buflist: - self.buf = self.buf + string.joinfields(self.buflist, '') + self.buf = self.buf + ''.join(self.buflist) self.buflist = [] - i = string.find(self.buf, '\n', self.pos) + i = self.buf.find('\n', self.pos) if i < 0: newpos = self.len else: @@ -134,7 +133,7 @@ class DBRecIO: self.pos = newpos def writelines(self, list): - self.write(string.joinfields(list, '')) + self.write(''.join(list)) def flush(self): if self.closed: diff --git a/Lib/bsddb/test/test_associate.py b/Lib/bsddb/test/test_associate.py index 857cd3d0ae1..d8c9c0c9b2a 100644 --- a/Lib/bsddb/test/test_associate.py +++ b/Lib/bsddb/test/test_associate.py @@ -2,7 +2,7 @@ TestCases for DB.associate. """ -import sys, os, string +import sys, os import tempfile import time from pprint import pprint @@ -177,7 +177,7 @@ class AssociateTestCase(unittest.TestCase): for key, value in musicdata.items(): if type(self.keytype) == type(''): key = "%02d" % key - d.put(key, string.join(value, '|'), txn=txn) + d.put(key, '|'.join(value), txn=txn) def createDB(self, txn=None): self.cur = None @@ -263,7 +263,7 @@ class AssociateTestCase(unittest.TestCase): rec = self.cur.first() while rec is not None: if type(self.keytype) == type(''): - assert string.atoi(rec[0]) # for primary db, key is a number + assert int(rec[0]) # for primary db, key is a number else: assert rec[0] and type(rec[0]) == type(0) count = count + 1 @@ -305,7 +305,7 @@ class AssociateTestCase(unittest.TestCase): assert type(priData) == type("") if verbose: print('getGenre key: %r data: %r' % (priKey, priData)) - genre = string.split(priData, '|')[2] + genre = priData.split('|')[2] if genre == 'Blues': return db.DB_DONOTINDEX else: @@ -427,13 +427,13 @@ class ThreadedAssociateTestCase(AssociateTestCase): for key, value in musicdata.items(): if type(self.keytype) == type(''): key = "%02d" % key - d.put(key, string.join(value, '|')) + d.put(key, '|'.join(value)) def writer2(self, d): for x in range(100, 600): key = 'z%2d' % x value = [key] * 4 - d.put(key, string.join(value, '|')) + d.put(key, '|'.join(value)) class ThreadedAssociateHashTestCase(ShelveAssociateTestCase): diff --git a/Lib/bsddb/test/test_compat.py b/Lib/bsddb/test/test_compat.py index 7561f9f01d0..29088446daa 100644 --- a/Lib/bsddb/test/test_compat.py +++ b/Lib/bsddb/test/test_compat.py @@ -3,7 +3,7 @@ Test cases adapted from the test_bsddb.py module in Python's regression test suite. """ -import sys, os, string +import sys, os import unittest import tempfile @@ -35,7 +35,7 @@ class CompatibilityTestCase(unittest.TestCase): self.do_bthash_test(hashopen, 'hashopen') def test03_rnopen(self): - data = string.split("The quick brown fox jumped over the lazy dog.") + data = "The quick brown fox jumped over the lazy dog.".split() if verbose: print("\nTesting: rnopen") diff --git a/Lib/bsddb/test/test_dbobj.py b/Lib/bsddb/test/test_dbobj.py index b15de2f0ef9..27fffe02e54 100644 --- a/Lib/bsddb/test/test_dbobj.py +++ b/Lib/bsddb/test/test_dbobj.py @@ -1,5 +1,5 @@ -import sys, os, string +import sys, os import unittest import glob import tempfile @@ -38,7 +38,7 @@ class dbobjTestCase(unittest.TestCase): class TestDBEnv(dbobj.DBEnv): pass class TestDB(dbobj.DB): def put(self, key, *args, **kwargs): - key = string.upper(key) + key = key.upper() # call our parent classes put method with an upper case key return dbobj.DB.put(self, key, *args, **kwargs) self.env = TestDBEnv() diff --git a/Lib/bsddb/test/test_join.py b/Lib/bsddb/test/test_join.py index 67507eabebf..00e7479efb5 100644 --- a/Lib/bsddb/test/test_join.py +++ b/Lib/bsddb/test/test_join.py @@ -1,7 +1,7 @@ """TestCases for using the DB.join and DBCursor.join_item methods. """ -import sys, os, string +import sys, os import tempfile import time from pprint import pprint diff --git a/Lib/bsddb/test/test_lock.py b/Lib/bsddb/test/test_lock.py index e44bf214a64..9b5a71f77d3 100644 --- a/Lib/bsddb/test/test_lock.py +++ b/Lib/bsddb/test/test_lock.py @@ -2,7 +2,7 @@ TestCases for testing the locking sub-system. """ -import sys, os, string +import sys, os import tempfile import time from pprint import pprint diff --git a/Lib/bsddb/test/test_pickle.py b/Lib/bsddb/test/test_pickle.py index 4683ec6d2a7..95cb23dadbc 100644 --- a/Lib/bsddb/test/test_pickle.py +++ b/Lib/bsddb/test/test_pickle.py @@ -1,5 +1,5 @@ -import sys, os, string +import sys, os import pickle try: import cPickle diff --git a/Lib/distutils/cmd.py b/Lib/distutils/cmd.py index be0a3e23f65..ebd99310ea7 100644 --- a/Lib/distutils/cmd.py +++ b/Lib/distutils/cmd.py @@ -8,7 +8,7 @@ in the distutils.command package. __revision__ = "$Id$" -import sys, os, string, re +import sys, os, re from types import * from distutils.errors import * from distutils import util, dir_util, file_util, archive_util, dep_util @@ -166,7 +166,7 @@ class Command: print(indent + header) indent = indent + " " for (option, _, _) in self.user_options: - option = string.translate(option, longopt_xlate) + option = option.translate(longopt_xlate) if option[-1] == "=": option = option[:-1] value = getattr(self, option) @@ -415,7 +415,7 @@ class Command: """ if exec_msg is None: exec_msg = "generating %s from %s" % \ - (outfile, string.join(infiles, ', ')) + (outfile, ', '.join(infiles)) if skip_msg is None: skip_msg = "skipping %s (inputs unchanged)" % outfile diff --git a/Lib/distutils/command/bdist.py b/Lib/distutils/command/bdist.py index 23c25a55a87..d6897d2d09b 100644 --- a/Lib/distutils/command/bdist.py +++ b/Lib/distutils/command/bdist.py @@ -7,7 +7,7 @@ distribution).""" __revision__ = "$Id$" -import os, string +import os from types import * from distutils.core import Command from distutils.errors import * diff --git a/Lib/distutils/command/bdist_msi.py b/Lib/distutils/command/bdist_msi.py index 75db8773f1e..f31bdedac6f 100644 --- a/Lib/distutils/command/bdist_msi.py +++ b/Lib/distutils/command/bdist_msi.py @@ -7,7 +7,7 @@ Implements the bdist_msi command. """ -import sys, os, string +import sys, os from distutils.core import Command from distutils.util import get_platform from distutils.dir_util import remove_tree diff --git a/Lib/distutils/command/bdist_rpm.py b/Lib/distutils/command/bdist_rpm.py index bbcf2927dc8..ef2bdfd808b 100644 --- a/Lib/distutils/command/bdist_rpm.py +++ b/Lib/distutils/command/bdist_rpm.py @@ -7,7 +7,7 @@ distributions).""" __revision__ = "$Id$" -import sys, os, string +import sys, os import glob from types import * from distutils.core import Command @@ -354,7 +354,7 @@ class bdist_rpm (Command): line = out.readline() if not line: break - l = string.split(string.strip(line)) + l = line.strip().split() assert(len(l) == 2) binary_rpms.append(l[1]) # The source rpm is named after the first entry in the spec file @@ -437,9 +437,9 @@ class bdist_rpm (Command): 'Conflicts', 'Obsoletes', ): - val = getattr(self, string.lower(field)) + val = getattr(self, field.lower()) if type(val) is ListType: - spec_file.append('%s: %s' % (field, string.join(val))) + spec_file.append('%s: %s' % (field, ' '.join(val))) elif val is not None: spec_file.append('%s: %s' % (field, val)) @@ -452,7 +452,7 @@ class bdist_rpm (Command): if self.build_requires: spec_file.append('BuildRequires: ' + - string.join(self.build_requires)) + ' '.join(self.build_requires)) if self.icon: spec_file.append('Icon: ' + os.path.basename(self.icon)) @@ -513,7 +513,7 @@ class bdist_rpm (Command): '', '%' + rpm_opt,]) if val: - spec_file.extend(string.split(open(val, 'r').read(), '\n')) + spec_file.extend(open(val, 'r').read().split('\n')) else: spec_file.append(default) @@ -526,7 +526,7 @@ class bdist_rpm (Command): ]) if self.doc_files: - spec_file.append('%doc ' + string.join(self.doc_files)) + spec_file.append('%doc ' + ' '.join(self.doc_files)) if self.changelog: spec_file.extend([ @@ -544,8 +544,8 @@ class bdist_rpm (Command): if not changelog: return changelog new_changelog = [] - for line in string.split(string.strip(changelog), '\n'): - line = string.strip(line) + for line in changelog.strip().split('\n'): + line = line.strip() if line[0] == '*': new_changelog.extend(['', line]) elif line[0] == '-': diff --git a/Lib/distutils/command/bdist_wininst.py b/Lib/distutils/command/bdist_wininst.py index 49afca0472a..21465a82ffd 100644 --- a/Lib/distutils/command/bdist_wininst.py +++ b/Lib/distutils/command/bdist_wininst.py @@ -7,7 +7,7 @@ exe-program.""" __revision__ = "$Id$" -import sys, os, string +import sys, os from distutils.core import Command from distutils.util import get_platform from distutils.dir_util import create_tree, remove_tree @@ -135,7 +135,7 @@ class bdist_wininst (Command): # Use a custom scheme for the zip-file, because we have to decide # at installation time which scheme to use. for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'): - value = string.upper(key) + value = key.upper() if key == 'headers': value = value + '/Include/$dist_name' setattr(install, @@ -192,14 +192,14 @@ class bdist_wininst (Command): # Escape newline characters def escape(s): - return string.replace(s, "\n", "\\n") + return s.replace("\n", "\\n") for name in ["author", "author_email", "description", "maintainer", "maintainer_email", "name", "url", "version"]: data = getattr(metadata, name, "") if data: info = info + ("\n %s: %s" % \ - (string.capitalize(name), escape(data))) + (name.capitalize(), escape(data))) lines.append("%s=%s" % (name, escape(data))) # The [setup] section contains entries controlling @@ -220,7 +220,7 @@ class bdist_wininst (Command): build_info = "Built %s with distutils-%s" % \ (time.ctime(time.time()), distutils.__version__) lines.append("build_info=%s" % build_info) - return string.join(lines, "\n") + return "\n".join(lines) # get_inidata() diff --git a/Lib/distutils/command/build_clib.py b/Lib/distutils/command/build_clib.py index 69d8c75166d..07f58179862 100644 --- a/Lib/distutils/command/build_clib.py +++ b/Lib/distutils/command/build_clib.py @@ -18,7 +18,7 @@ __revision__ = "$Id$" # two modules, mainly because a number of subtle details changed in the # cut 'n paste. Sigh. -import os, string +import os from types import * from distutils.core import Command from distutils.errors import * @@ -93,8 +93,7 @@ class build_clib (Command): if self.include_dirs is None: self.include_dirs = self.distribution.include_dirs or [] if type(self.include_dirs) is StringType: - self.include_dirs = string.split(self.include_dirs, - os.pathsep) + self.include_dirs = self.include_dirs.split(os.pathsep) # XXX same as for build_ext -- what about 'self.define' and # 'self.undef' ? diff --git a/Lib/distutils/command/build_ext.py b/Lib/distutils/command/build_ext.py index bbe514626d0..d0cd16293b1 100644 --- a/Lib/distutils/command/build_ext.py +++ b/Lib/distutils/command/build_ext.py @@ -8,7 +8,7 @@ extensions ASAP).""" __revision__ = "$Id$" -import sys, os, string, re +import sys, os, re from types import * from distutils.core import Command from distutils.errors import * @@ -138,7 +138,7 @@ class build_ext (Command): if self.include_dirs is None: self.include_dirs = self.distribution.include_dirs or [] if type(self.include_dirs) is StringType: - self.include_dirs = string.split(self.include_dirs, os.pathsep) + self.include_dirs = self.include_dirs.split(os.pathsep) # Put the Python "system" include dir at the end, so that # any local include dirs take precedence. @@ -156,12 +156,12 @@ class build_ext (Command): if self.library_dirs is None: self.library_dirs = [] elif type(self.library_dirs) is StringType: - self.library_dirs = string.split(self.library_dirs, os.pathsep) + self.library_dirs = self.library_dirs.split(os.pathsep) if self.rpath is None: self.rpath = [] elif type(self.rpath) is StringType: - self.rpath = string.split(self.rpath, os.pathsep) + self.rpath = self.rpath.split(os.pathsep) # for extensions under windows use different directories # for Release and Debug builds. @@ -186,7 +186,7 @@ class build_ext (Command): # for extensions under Cygwin and AtheOS Python's library directory must be # appended to library_dirs if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos': - if string.find(sys.executable, sys.exec_prefix) != -1: + if sys.executable.find(sys.exec_prefix) != -1: # building third party extensions self.library_dirs.append(os.path.join(sys.prefix, "lib", "python" + get_python_version(), @@ -199,7 +199,7 @@ class build_ext (Command): # Python's library directory must be appended to library_dirs if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \ and sysconfig.get_config_var('Py_ENABLE_SHARED'): - if string.find(sys.executable, sys.exec_prefix) != -1: + if sys.executable.find(sys.exec_prefix) != -1: # building third party extensions self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) else: @@ -212,14 +212,14 @@ class build_ext (Command): # symbols can be separated with commas. if self.define: - defines = string.split(self.define, ',') + defines = self.define.split(',') self.define = map(lambda symbol: (symbol, '1'), defines) # The option for macros to undefine is also a string from the # option parsing, but has to be a list. Multiple symbols can also # be separated with commas here. if self.undef: - self.undef = string.split(self.undef, ',') + self.undef = self.undef.split(',') if self.swig_opts is None: self.swig_opts = [] @@ -429,8 +429,8 @@ class build_ext (Command): # ignore build-lib -- put the compiled extension into # the source tree along with pure Python modules - modpath = string.split(fullname, '.') - package = string.join(modpath[0:-1], '.') + modpath = fullname.split('.') + package = '.'.join(modpath[0:-1]) base = modpath[-1] build_py = self.get_finalized_command('build_py') @@ -617,7 +617,7 @@ class build_ext (Command): """ from distutils.sysconfig import get_config_var - ext_path = string.split(ext_name, '.') + ext_path = ext_name.split('.') # OS/2 has an 8 character module (extension) limit :-( if os.name == "os2": ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8] @@ -634,7 +634,7 @@ class build_ext (Command): the .pyd file (DLL) must export the module "init" function. """ - initfunc_name = "init" + string.split(ext.name,'.')[-1] + initfunc_name = "init" + ext.name.split('.')[-1] if initfunc_name not in ext.export_symbols: ext.export_symbols.append(initfunc_name) return ext.export_symbols diff --git a/Lib/distutils/command/build_py.py b/Lib/distutils/command/build_py.py index 3b7ec62c599..990824bdff7 100644 --- a/Lib/distutils/command/build_py.py +++ b/Lib/distutils/command/build_py.py @@ -6,7 +6,7 @@ Implements the Distutils 'build_py' command.""" __revision__ = "$Id$" -import sys, string, os +import sys, os from types import * from glob import glob @@ -150,7 +150,7 @@ class build_py (Command): distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any).""" - path = string.split(package, '.') + path = package.split('.') if not self.package_dir: if path: @@ -161,7 +161,7 @@ class build_py (Command): tail = [] while path: try: - pdir = self.package_dir[string.join(path, '.')] + pdir = self.package_dir['.'.join(path)] except KeyError: tail.insert(0, path[-1]) del path[-1] @@ -272,8 +272,8 @@ class build_py (Command): # - don't check for __init__.py in directory for empty package for module in self.py_modules: - path = string.split(module, '.') - package = string.join(path[0:-1], '.') + path = module.split('.') + package = '.'.join(path[0:-1]) module_base = path[-1] try: @@ -342,7 +342,7 @@ class build_py (Command): modules = self.find_all_modules() outputs = [] for (package, module, module_file) in modules: - package = string.split(package, '.') + package = package.split('.') filename = self.get_module_outfile(self.build_lib, package, module) outputs.append(filename) if include_bytecode: @@ -362,7 +362,7 @@ class build_py (Command): def build_module (self, module, module_file, package): if type(package) is StringType: - package = string.split(package, '.') + package = package.split('.') elif type(package) not in (ListType, TupleType): raise TypeError, \ "'package' must be a string (dot-separated), list, or tuple" diff --git a/Lib/distutils/command/config.py b/Lib/distutils/command/config.py index 42465693be7..3374db9e66f 100644 --- a/Lib/distutils/command/config.py +++ b/Lib/distutils/command/config.py @@ -13,7 +13,7 @@ this header file lives". __revision__ = "$Id$" -import sys, os, string, re +import sys, os, re from types import * from distutils.core import Command from distutils.errors import DistutilsExecError @@ -74,7 +74,7 @@ class config (Command): if self.include_dirs is None: self.include_dirs = self.distribution.include_dirs or [] elif type(self.include_dirs) is StringType: - self.include_dirs = string.split(self.include_dirs, os.pathsep) + self.include_dirs = self.include_dirs.split(os.pathsep) if self.libraries is None: self.libraries = [] @@ -84,7 +84,7 @@ class config (Command): if self.library_dirs is None: self.library_dirs = [] elif type(self.library_dirs) is StringType: - self.library_dirs = string.split(self.library_dirs, os.pathsep) + self.library_dirs = self.library_dirs.split(os.pathsep) def run (self): @@ -163,7 +163,7 @@ class config (Command): if not filenames: filenames = self.temp_files self.temp_files = [] - log.info("removing: %s", string.join(filenames)) + log.info("removing: %s", ' '.join(filenames)) for filename in filenames: try: os.remove(filename) @@ -322,7 +322,7 @@ class config (Command): else: body.append(" %s;" % func) body.append("}") - body = string.join(body, "\n") + "\n" + body = "\n".join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) diff --git a/Lib/distutils/command/install.py b/Lib/distutils/command/install.py index fd5d6d1f39c..c03a90e82c2 100644 --- a/Lib/distutils/command/install.py +++ b/Lib/distutils/command/install.py @@ -8,7 +8,7 @@ from distutils import log __revision__ = "$Id$" -import sys, os, string +import sys, os from types import * from distutils.core import Command from distutils.debug import DEBUG @@ -269,7 +269,7 @@ class install (Command): # $platbase in the other installation directories and not worry # about needing recursive variable expansion (shudder). - py_version = (string.split(sys.version))[0] + py_version = sys.version.split()[0] (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix') self.config_vars = {'dist_name': self.distribution.get_name(), 'dist_version': self.distribution.get_version(), @@ -353,11 +353,11 @@ class install (Command): if opt_name[-1] == "=": opt_name = opt_name[0:-1] if self.negative_opt.has_key(opt_name): - opt_name = string.translate(self.negative_opt[opt_name], - longopt_xlate) + opt_name = self.negative_opt[opt_name].translate( + longopt_xlate) val = not getattr(self, opt_name) else: - opt_name = string.translate(opt_name, longopt_xlate) + opt_name = opt_name.translate(longopt_xlate) val = getattr(self, opt_name) print(" %s: %s" % (opt_name, val)) @@ -464,7 +464,7 @@ class install (Command): if self.extra_path is not None: if type(self.extra_path) is StringType: - self.extra_path = string.split(self.extra_path, ',') + self.extra_path = self.extra_path.split(',') if len(self.extra_path) == 1: path_file = extra_dirs = self.extra_path[0] diff --git a/Lib/distutils/command/install_lib.py b/Lib/distutils/command/install_lib.py index 08ff543449c..65d25f7af24 100644 --- a/Lib/distutils/command/install_lib.py +++ b/Lib/distutils/command/install_lib.py @@ -2,7 +2,7 @@ __revision__ = "$Id$" -import sys, os, string +import sys, os from types import IntType from distutils.core import Command from distutils.errors import DistutilsOptionError diff --git a/Lib/distutils/command/register.py b/Lib/distutils/command/register.py index 48070ee83b1..33567981bb8 100644 --- a/Lib/distutils/command/register.py +++ b/Lib/distutils/command/register.py @@ -7,7 +7,7 @@ Implements the Distutils 'register' command (register with the repository). __revision__ = "$Id$" -import sys, os, string, urllib2, getpass, urlparse +import sys, os, urllib2, getpass, urlparse import StringIO, ConfigParser from distutils.core import Command @@ -67,7 +67,7 @@ class register(Command): if missing: self.warn("missing required meta-data: " + - string.join(missing, ", ")) + ", ".join(missing)) if metadata.author: if not metadata.author_email: diff --git a/Lib/distutils/command/sdist.py b/Lib/distutils/command/sdist.py index eb2db505ddd..8e1c066023e 100644 --- a/Lib/distutils/command/sdist.py +++ b/Lib/distutils/command/sdist.py @@ -6,7 +6,7 @@ Implements the Distutils 'sdist' command (create a source distribution).""" __revision__ = "$Id$" -import sys, os, string +import sys, os from types import * from glob import glob from distutils.core import Command @@ -166,7 +166,7 @@ class sdist (Command): if missing: self.warn("missing required meta-data: " + - string.join(missing, ", ")) + ", ".join(missing)) if metadata.author: if not metadata.author_email: @@ -279,7 +279,7 @@ class sdist (Command): if not got_it: self.warn("standard file not found: should have one of " + - string.join(alts, ', ')) + ', '.join(alts)) else: if os.path.exists(fn): self.filelist.append(fn) diff --git a/Lib/distutils/cygwinccompiler.py b/Lib/distutils/cygwinccompiler.py index 44b5850834b..fae68481655 100644 --- a/Lib/distutils/cygwinccompiler.py +++ b/Lib/distutils/cygwinccompiler.py @@ -365,10 +365,9 @@ def check_config_h(): # "pyconfig.h" check -- should probably be renamed... from distutils import sysconfig - import string # if sys.version contains GCC then python was compiled with # GCC, and the pyconfig.h file should be OK - if string.find(sys.version,"GCC") >= 0: + if sys.version.find("GCC") >= 0: return (CONFIG_H_OK, "sys.version mentions 'GCC'") fn = sysconfig.get_config_h_filename() @@ -387,7 +386,7 @@ def check_config_h(): else: # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar - if string.find(s,"__GNUC__") >= 0: + if s.find("__GNUC__") >= 0: return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn) else: return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn) diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py index ca7a2f9952f..7ed1b5cf2c6 100644 --- a/Lib/distutils/dist.py +++ b/Lib/distutils/dist.py @@ -8,7 +8,7 @@ being built/installed/distributed. __revision__ = "$Id$" -import sys, os, string, re +import sys, os, re from types import * from copy import copy @@ -304,7 +304,7 @@ Common commands: (see '--help-commands' for more) else: print(indent + "option dict for '%s' command:" % cmd_name) out = pformat(opt_dict) - for line in string.split(out, "\n"): + for line in out.split("\n"): print(indent + " " + line) # dump_option_dicts () @@ -378,7 +378,7 @@ Common commands: (see '--help-commands' for more) for opt in options: if opt != '__name__': val = parser.get(section,opt) - opt = string.replace(opt, '-', '_') + opt = opt.replace('-', '_') opt_dict[opt] = (filename, val) # Make the ConfigParser forget everything (so we retain @@ -599,14 +599,14 @@ Common commands: (see '--help-commands' for more) keywords = self.metadata.keywords if keywords is not None: if type(keywords) is StringType: - keywordlist = string.split(keywords, ',') - self.metadata.keywords = map(string.strip, keywordlist) + keywordlist = keywords.split(',') + self.metadata.keywords = [x.strip() for x in keywordlist] platforms = self.metadata.platforms if platforms is not None: if type(platforms) is StringType: - platformlist = string.split(platforms, ',') - self.metadata.platforms = map(string.strip, platformlist) + platformlist = platforms.split(',') + self.metadata.platforms = [x.strip() for x in platformlist] def _show_help (self, parser, @@ -695,10 +695,10 @@ Common commands: (see '--help-commands' for more) opt = translate_longopt(opt) value = getattr(self.metadata, "get_"+opt)() if opt in ['keywords', 'platforms']: - print(string.join(value, ',')) + print(','.join(value)) elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'): - print(string.join(value, '\n')) + print('\n'.join(value)) else: print(value) any_display_options = 1 @@ -803,9 +803,9 @@ Common commands: (see '--help-commands' for more) """Return a list of packages from which commands are loaded.""" pkgs = self.command_packages if not isinstance(pkgs, type([])): - pkgs = string.split(pkgs or "", ",") + pkgs = (pkgs or "").split(",") for i in range(len(pkgs)): - pkgs[i] = string.strip(pkgs[i]) + pkgs[i] = pkgs[i].strip() pkgs = filter(None, pkgs) if "distutils.command" not in pkgs: pkgs.insert(0, "distutils.command") @@ -1100,7 +1100,7 @@ class DistributionMetadata: long_desc = rfc822_escape( self.get_long_description() ) file.write('Description: %s\n' % long_desc) - keywords = string.join( self.get_keywords(), ',') + keywords = ','.join(self.get_keywords()) if keywords: file.write('Keywords: %s\n' % keywords ) diff --git a/Lib/distutils/emxccompiler.py b/Lib/distutils/emxccompiler.py index 8aef2b7a9db..f4b90dcd00d 100644 --- a/Lib/distutils/emxccompiler.py +++ b/Lib/distutils/emxccompiler.py @@ -261,10 +261,9 @@ def check_config_h(): # "pyconfig.h" check -- should probably be renamed... from distutils import sysconfig - import string # if sys.version contains GCC then python was compiled with # GCC, and the pyconfig.h file should be OK - if string.find(sys.version,"GCC") >= 0: + if sys.version.find("GCC") >= 0: return (CONFIG_H_OK, "sys.version mentions 'GCC'") fn = sysconfig.get_config_h_filename() @@ -283,7 +282,7 @@ def check_config_h(): else: # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar - if string.find(s,"__GNUC__") >= 0: + if s.find("__GNUC__") >= 0: return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn) else: return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn) diff --git a/Lib/distutils/extension.py b/Lib/distutils/extension.py index 440d128cdc6..0fcbcc141af 100644 --- a/Lib/distutils/extension.py +++ b/Lib/distutils/extension.py @@ -5,7 +5,7 @@ modules in setup scripts.""" __revision__ = "$Id$" -import os, string, sys +import os, sys from types import * try: @@ -128,7 +128,7 @@ class Extension: if len(kw): L = kw.keys() ; L.sort() L = map(repr, L) - msg = "Unknown Extension options: " + string.join(L, ', ') + msg = "Unknown Extension options: " + ', '.join(L) if warnings is not None: warnings.warn(msg) else: @@ -195,7 +195,7 @@ def read_setup_file (filename): elif switch == "-I": ext.include_dirs.append(value) elif switch == "-D": - equals = string.find(value, "=") + equals = value.find("=") if equals == -1: # bare "-DFOO" -- no value ext.define_macros.append((value, None)) else: # "-DFOO=blah" diff --git a/Lib/distutils/fancy_getopt.py b/Lib/distutils/fancy_getopt.py index 646f8e1ee6f..317a3a4860d 100644 --- a/Lib/distutils/fancy_getopt.py +++ b/Lib/distutils/fancy_getopt.py @@ -115,7 +115,7 @@ class FancyGetopt: """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" - return string.translate(long_option, longopt_xlate) + return long_option.translate(longopt_xlate) def _check_alias_dict (self, aliases, what): @@ -253,7 +253,7 @@ class FancyGetopt: self._grok_option_table() - short_opts = string.join(self.short_opts) + short_opts = ' '.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) except getopt.error as msg: @@ -420,8 +420,8 @@ def wrap_text (text, width): if len(text) <= width: return [text] - text = string.expandtabs(text) - text = string.translate(text, WS_TRANS) + text = text.expandtabs() + text = text.translate(WS_TRANS) chunks = re.split(r'( +|-+)', text) chunks = filter(None, chunks) # ' - ' results in empty strings lines = [] @@ -460,7 +460,7 @@ def wrap_text (text, width): # and store this line in the list-of-all-lines -- as a single # string, of course! - lines.append(string.join(cur_line, '')) + lines.append(''.join(cur_line)) # while chunks @@ -473,7 +473,7 @@ def translate_longopt (opt): """Convert a long option name to a valid Python identifier by changing "-" to "_". """ - return string.translate(opt, longopt_xlate) + return opt.translate(longopt_xlate) class OptionDummy: @@ -498,5 +498,5 @@ say, "How should I know?"].)""" for w in (10, 20, 30, 40): print("width: %d" % w) - print(string.join(wrap_text(text, w), "\n")) + print("\n".join(wrap_text(text, w))) print() diff --git a/Lib/distutils/filelist.py b/Lib/distutils/filelist.py index e4a83d6484e..bc668cfad34 100644 --- a/Lib/distutils/filelist.py +++ b/Lib/distutils/filelist.py @@ -8,7 +8,7 @@ and building lists of files. __revision__ = "$Id$" -import os, string, re +import os, re import fnmatch from types import * from glob import glob @@ -84,7 +84,7 @@ class FileList: # -- "File template" methods --------------------------------------- def _parse_template_line (self, line): - words = string.split(line) + words = line.split() action = words[0] patterns = dir = dir_pattern = None @@ -133,28 +133,28 @@ class FileList: # right number of words on the line for that action -- so we # can proceed with minimal error-checking. if action == 'include': - self.debug_print("include " + string.join(patterns)) + self.debug_print("include " + ' '.join(patterns)) for pattern in patterns: if not self.include_pattern(pattern, anchor=1): log.warn("warning: no files found matching '%s'", pattern) elif action == 'exclude': - self.debug_print("exclude " + string.join(patterns)) + self.debug_print("exclude " + ' '.join(patterns)) for pattern in patterns: if not self.exclude_pattern(pattern, anchor=1): log.warn(("warning: no previously-included files " "found matching '%s'"), pattern) elif action == 'global-include': - self.debug_print("global-include " + string.join(patterns)) + self.debug_print("global-include " + ' '.join(patterns)) for pattern in patterns: if not self.include_pattern(pattern, anchor=0): log.warn(("warning: no files found matching '%s' " + "anywhere in distribution"), pattern) elif action == 'global-exclude': - self.debug_print("global-exclude " + string.join(patterns)) + self.debug_print("global-exclude " + ' '.join(patterns)) for pattern in patterns: if not self.exclude_pattern(pattern, anchor=0): log.warn(("warning: no previously-included files matching " @@ -163,7 +163,7 @@ class FileList: elif action == 'recursive-include': self.debug_print("recursive-include %s %s" % - (dir, string.join(patterns))) + (dir, ' '.join(patterns))) for pattern in patterns: if not self.include_pattern(pattern, prefix=dir): log.warn(("warning: no files found matching '%s' " + @@ -172,7 +172,7 @@ class FileList: elif action == 'recursive-exclude': self.debug_print("recursive-exclude %s %s" % - (dir, string.join(patterns))) + (dir, ' '.join(patterns))) for pattern in patterns: if not self.exclude_pattern(pattern, prefix=dir): log.warn(("warning: no previously-included files matching " diff --git a/Lib/distutils/msvccompiler.py b/Lib/distutils/msvccompiler.py index 968a4ffd462..ca1feaa0886 100644 --- a/Lib/distutils/msvccompiler.py +++ b/Lib/distutils/msvccompiler.py @@ -12,7 +12,7 @@ for the Microsoft Visual Studio. __revision__ = "$Id$" -import sys, os, string +import sys, os from distutils.errors import \ DistutilsExecError, DistutilsPlatformError, \ CompileError, LibError, LinkError @@ -148,7 +148,7 @@ you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""") def sub(self, s): for k, v in self.macros.items(): - s = string.replace(s, k, v) + s = s.replace(k, v) return s def get_build_version(): @@ -159,7 +159,7 @@ def get_build_version(): """ prefix = "MSC v." - i = string.find(sys.version, prefix) + i = sys.version.find(prefix) if i == -1: return 6 i = i + len(prefix) @@ -181,10 +181,10 @@ def get_build_architecture(): """ prefix = " bit (" - i = string.find(sys.version, prefix) + i = sys.version.find(prefix) if i == -1: return "Intel" - j = string.find(sys.version, ")", i) + j = sys.version.find(")", i) return sys.version[i+len(prefix):j] @@ -266,11 +266,11 @@ class MSVCCompiler (CCompiler) : # extend the MSVC path with the current path try: - for p in string.split(os.environ['path'], ';'): + for p in os.environ['path'].split(';'): self.__paths.append(p) except KeyError: pass - os.environ['path'] = string.join(self.__paths, ';') + os.environ['path'] = ';'.join(self.__paths) self.preprocess_options = None if self.__arch == "Intel": @@ -579,7 +579,7 @@ class MSVCCompiler (CCompiler) : return fn # didn't find it; try existing path - for p in string.split(os.environ['Path'],';'): + for p in os.environ['Path'].split(';'): fn = os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn @@ -608,9 +608,9 @@ class MSVCCompiler (CCompiler) : d = read_values(base, key) if d: if self.__version >= 7: - return string.split(self.__macros.sub(d[path]), ";") + return self.__macros.sub(d[path]).split(";") else: - return string.split(d[path], ";") + return d[path].split(";") # MSVC 6 seems to create the registry entries we need only when # the GUI is run. if self.__version == 6: @@ -635,4 +635,4 @@ class MSVCCompiler (CCompiler) : else: p = self.get_msvc_paths(name) if p: - os.environ[name] = string.join(p, ';') + os.environ[name] = ';'.join(p) diff --git a/Lib/distutils/mwerkscompiler.py b/Lib/distutils/mwerkscompiler.py index 9db1a39b17c..028ea8250d2 100644 --- a/Lib/distutils/mwerkscompiler.py +++ b/Lib/distutils/mwerkscompiler.py @@ -8,7 +8,7 @@ Windows.""" __revision__ = "$Id$" -import sys, os, string +import sys, os from types import * from distutils.errors import \ DistutilsExecError, DistutilsPlatformError, \ @@ -213,11 +213,11 @@ class MWerksCompiler (CCompiler) : curdir = os.getcwd() filename = os.path.join(curdir, filename) # Finally remove .. components - components = string.split(filename, ':') + components = filename.split(':') for i in range(1, len(components)): if components[i] == '..': components[i] = '' - return string.join(components, ':') + return ':'.join(components) def library_dir_option (self, dir): """Return the compiler option to add 'dir' to the list of diff --git a/Lib/distutils/spawn.py b/Lib/distutils/spawn.py index c75931c3abf..c70c10bf7c5 100644 --- a/Lib/distutils/spawn.py +++ b/Lib/distutils/spawn.py @@ -10,7 +10,7 @@ executable name. __revision__ = "$Id$" -import sys, os, string +import sys, os from distutils.errors import * from distutils import log @@ -59,7 +59,7 @@ def _nt_quote_args (args): # quoting?) for i in range(len(args)): - if string.find(args[i], ' ') != -1: + if args[i].find(' ') != -1: args[i] = '"%s"' % args[i] return args @@ -73,7 +73,7 @@ def _spawn_nt (cmd, if search_path: # either we find one or it stays the same executable = find_executable(executable) or executable - log.info(string.join([executable] + cmd[1:], ' ')) + log.info(' '.join([executable] + cmd[1:])) if not dry_run: # spawn for NT requires a full path to the .exe try: @@ -98,7 +98,7 @@ def _spawn_os2 (cmd, if search_path: # either we find one or it stays the same executable = find_executable(executable) or executable - log.info(string.join([executable] + cmd[1:], ' ')) + log.info(' '.join([executable] + cmd[1:])) if not dry_run: # spawnv for OS/2 EMX requires a full path to the .exe try: @@ -119,7 +119,7 @@ def _spawn_posix (cmd, verbose=0, dry_run=0): - log.info(string.join(cmd, ' ')) + log.info(' '.join(cmd)) if dry_run: return exec_fn = search_path and os.execvp or os.execv @@ -184,7 +184,7 @@ def find_executable(executable, path=None): """ if path is None: path = os.environ['PATH'] - paths = string.split(path, os.pathsep) + paths = path.split(os.pathsep) (base, ext) = os.path.splitext(executable) if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'): executable = executable + '.exe' diff --git a/Lib/distutils/sysconfig.py b/Lib/distutils/sysconfig.py index 220b03310c3..ea2e0597788 100644 --- a/Lib/distutils/sysconfig.py +++ b/Lib/distutils/sysconfig.py @@ -13,7 +13,6 @@ __revision__ = "$Id$" import os import re -import string import sys from .errors import DistutilsPlatformError @@ -261,7 +260,7 @@ def parse_makefile(fn, g=None): m = _variable_rx.match(line) if m: n, v = m.group(1, 2) - v = string.strip(v) + v = v.strip() if "$" in v: notdone[n] = v else: @@ -295,7 +294,7 @@ def parse_makefile(fn, g=None): else: try: value = int(value) except ValueError: - done[name] = string.strip(value) + done[name] = value.strip() else: done[name] = value del notdone[name] @@ -399,7 +398,7 @@ def _init_posix(): # relative to the srcdir, which after installation no longer makes # sense. python_lib = get_python_lib(standard_lib=1) - linkerscript_path = string.split(g['LDSHARED'])[0] + linkerscript_path = g['LDSHARED'].split()[0] linkerscript_name = os.path.basename(linkerscript_path) linkerscript = os.path.join(python_lib, 'config', linkerscript_name) diff --git a/Lib/distutils/text_file.py b/Lib/distutils/text_file.py index 10ee1be783b..c23a31dd9cd 100644 --- a/Lib/distutils/text_file.py +++ b/Lib/distutils/text_file.py @@ -7,7 +7,7 @@ lines, and joining lines with backslashes.""" __revision__ = "$Id$" from types import * -import sys, os, string +import sys, os class TextFile: @@ -142,7 +142,7 @@ class TextFile: else: outmsg.append("line %d: " % line) outmsg.append(str(msg)) - return string.join(outmsg, "") + return "".join(outmsg) def error (self, msg, line=None): @@ -196,7 +196,7 @@ class TextFile: # unescape it (and any other escaped "#"'s that might be # lurking in there) and otherwise leave the line alone. - pos = string.find (line, "#") + pos = line.find ("#") if pos == -1: # no "#" -- no comments pass @@ -219,11 +219,11 @@ class TextFile: # # comment that should be ignored # there # result in "hello there". - if string.strip(line) == "": + if line.strip () == "": continue else: # it's an escaped "#" - line = string.replace (line, "\\#", "#") + line = line.replace("\\#", "#") # did previous line end with a backslash? then accumulate @@ -235,7 +235,7 @@ class TextFile: return buildup_line if self.collapse_join: - line = string.lstrip (line) + line = line.lstrip () line = buildup_line + line # careful: pay attention to line number when incrementing it @@ -259,11 +259,11 @@ class TextFile: # strip whitespace however the client wants (leading and # trailing, or one or the other, or neither) if self.lstrip_ws and self.rstrip_ws: - line = string.strip (line) + line = line.strip () elif self.lstrip_ws: - line = string.lstrip (line) + line = line.lstrip () elif self.rstrip_ws: - line = string.rstrip (line) + line = line.rstrip () # blank line (whether we rstrip'ed or not)? skip to next line # if appropriate @@ -313,7 +313,7 @@ line 3 \\ continues on next line """ # result 1: no fancy options - result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1]) + result1 = map (lambda x: x + "\n", test_data.split ("\n")[0:-1]) # result 2: just strip comments result2 = ["\n", @@ -340,7 +340,7 @@ line 3 \\ def test_input (count, description, file, expected_result): result = file.readlines () - # result = string.join (result, '') + # result = ''.join (result) if result == expected_result: print("ok %d (%s)" % (count, description)) else: diff --git a/Lib/distutils/util.py b/Lib/distutils/util.py index 16d8bcba4d5..6f15ce8b5ed 100644 --- a/Lib/distutils/util.py +++ b/Lib/distutils/util.py @@ -42,10 +42,9 @@ def get_platform (): # Convert the OS name to lowercase, remove '/' characters # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") - osname = string.lower(osname) - osname = string.replace(osname, '/', '') - machine = string.replace(machine, ' ', '_') - machine = string.replace(machine, '/', '-') + osname = osname.lower().replace('/', '') + machine = machine.replace(' ', '_') + machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- @@ -139,7 +138,7 @@ def convert_path (pathname): if pathname[-1] == '/': raise ValueError, "path '%s' cannot end with '/'" % pathname - paths = string.split(pathname, '/') + paths = pathname.split('/') while '.' in paths: paths.remove('.') if not paths: @@ -178,7 +177,7 @@ def change_root (new_root, pathname): return os.path.join(new_root, pathname) else: # Chop off volume name from start of path - elements = string.split(pathname, ":", 1) + elements = pathname.split(":", 1) pathname = ":" + elements[1] return os.path.join(new_root, pathname) @@ -281,7 +280,7 @@ def split_quoted (s): # bit of a brain-bender to get it working right, though... if _wordchars_re is None: _init_regex() - s = string.strip(s) + s = s.strip() words = [] pos = 0 @@ -294,7 +293,7 @@ def split_quoted (s): if s[end] in string.whitespace: # unescaped, unquoted whitespace: now words.append(s[:end]) # we definitely have a word delimiter - s = string.lstrip(s[end:]) + s = s[end:].lstrip() pos = 0 elif s[end] == '\\': # preserve whatever is being escaped; @@ -354,7 +353,7 @@ def strtobool (val): are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ - val = string.lower(val) + val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return 1 elif val in ('n', 'no', 'f', 'false', 'off', '0'): @@ -445,7 +444,7 @@ files = [ #if prefix: # prefix = os.path.abspath(prefix) - script.write(string.join(map(repr, py_files), ",\n") + "]\n") + script.write(",\n".join(map(repr, py_files)) + "]\n") script.write(""" byte_compile(files, optimize=%r, force=%r, prefix=%r, base_dir=%r, @@ -507,7 +506,6 @@ def rfc822_escape (header): """Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline. """ - lines = string.split(header, '\n') - lines = map(string.strip, lines) - header = string.join(lines, '\n' + 8*' ') - return header + lines = [x.strip() for x in header.split('\n')] + sep = '\n' + 8*' ' + return sep.join(lines) diff --git a/Lib/distutils/version.py b/Lib/distutils/version.py index 2cd36365e75..2db6b18f1e6 100644 --- a/Lib/distutils/version.py +++ b/Lib/distutils/version.py @@ -26,8 +26,7 @@ Every version number class implements the following interface: of the same class, thus must follow the same rules) """ -import string, re -from types import StringType +import re class Version: """Abstract base class for version numbering classes. Just provides @@ -147,12 +146,12 @@ class StrictVersion (Version): match.group(1, 2, 4, 5, 6) if patch: - self.version = tuple(map(string.atoi, [major, minor, patch])) + self.version = tuple(map(int, [major, minor, patch])) else: - self.version = tuple(map(string.atoi, [major, minor]) + [0]) + self.version = tuple(map(int, [major, minor]) + [0]) if prerelease: - self.prerelease = (prerelease[0], string.atoi(prerelease_num)) + self.prerelease = (prerelease[0], int(prerelease_num)) else: self.prerelease = None @@ -160,9 +159,9 @@ class StrictVersion (Version): def __str__ (self): if self.version[2] == 0: - vstring = string.join(map(str, self.version[0:2]), '.') + vstring = '.'.join(map(str, self.version[0:2])) else: - vstring = string.join(map(str, self.version), '.') + vstring = '.'.join(map(str, self.version)) if self.prerelease: vstring = vstring + self.prerelease[0] + str(self.prerelease[1]) @@ -171,7 +170,7 @@ class StrictVersion (Version): def __cmp__ (self, other): - if isinstance(other, StringType): + if isinstance(other, str): other = StrictVersion(other) compare = cmp(self.version, other.version) @@ -327,7 +326,7 @@ class LooseVersion (Version): def __cmp__ (self, other): - if isinstance(other, StringType): + if isinstance(other, str): other = LooseVersion(other) return cmp(self.version, other.version) diff --git a/Lib/idlelib/Debugger.py b/Lib/idlelib/Debugger.py index f56460aad09..df691ed9c56 100644 --- a/Lib/idlelib/Debugger.py +++ b/Lib/idlelib/Debugger.py @@ -348,8 +348,7 @@ class StackViewer(ScrolledList): funcname = code.co_name import linecache sourceline = linecache.getline(filename, lineno) - import string - sourceline = string.strip(sourceline) + sourceline = sourceline.strip() if funcname in ("?", "", None): item = "%s, line %d: %s" % (modname, lineno, sourceline) else: diff --git a/Lib/idlelib/MultiCall.py b/Lib/idlelib/MultiCall.py index 1bb15768536..61730b8b2e0 100644 --- a/Lib/idlelib/MultiCall.py +++ b/Lib/idlelib/MultiCall.py @@ -31,7 +31,6 @@ Each function will be called at most once for each event. import sys import os -import string import re import Tkinter @@ -244,7 +243,7 @@ def _parse_sequence(sequence): """ if not sequence or sequence[0] != '<' or sequence[-1] != '>': return None - words = string.split(sequence[1:-1], '-') + words = '-'.split(sequence[1:-1]) modifiers = 0 while words and words[0] in _modifier_names: diff --git a/Lib/idlelib/aboutDialog.py b/Lib/idlelib/aboutDialog.py index c1210612e67..afdafd28444 100644 --- a/Lib/idlelib/aboutDialog.py +++ b/Lib/idlelib/aboutDialog.py @@ -3,7 +3,7 @@ """ from Tkinter import * -import string, os +import os import textView import idlever @@ -70,7 +70,7 @@ class AboutDialog(Toplevel): tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:] if tkVer[len(tkVer)-1] == '': tkVer[len(tkVer)-1] = '0' - tkVer = string.join(tkVer,'.') + tkVer = '.'.join(tkVer) labelTkVer = Label(frameBg, text='Tk version: '+ tkVer, fg=self.fg, bg=self.bg) labelTkVer.grid(row=9, column=1, sticky=W, padx=2, pady=0) diff --git a/Lib/idlelib/configDialog.py b/Lib/idlelib/configDialog.py index c1cbf82c1e8..eadb69dcd11 100644 --- a/Lib/idlelib/configDialog.py +++ b/Lib/idlelib/configDialog.py @@ -11,7 +11,7 @@ Refer to comments in EditorWindow autoindent code for details. """ from Tkinter import * import tkMessageBox, tkColorChooser, tkFont -import string, copy +import copy from configHandler import idleConf from dynOptionMenuWidget import DynOptionMenu @@ -650,7 +650,7 @@ class ConfigDialog(Toplevel): newKeys={} for event in prevKeys.keys(): #add key set to changed items eventName=event[2:-2] #trim off the angle brackets - binding=string.join(prevKeys[event]) + binding=' '.join(prevKeys[event]) newKeys[eventName]=binding #handle any unsaved changes to prev key set if prevKeySetName in self.changedItems['keys'].keys(): @@ -677,7 +677,7 @@ class ConfigDialog(Toplevel): bindNames.sort() self.listBindings.delete(0,END) for bindName in bindNames: - key=string.join(keySet[bindName]) #make key(s) into a string + key=' '.join(keySet[bindName]) #make key(s) into a string bindName=bindName[2:-2] #trim off the angle brackets if keySetName in self.changedItems['keys'].keys(): #handle any unsaved changes to this key set @@ -914,7 +914,7 @@ class ConfigDialog(Toplevel): self.changedItems['main']['HelpFiles'] = {} for num in range(1,len(self.userHelpList)+1): self.AddChangedItem('main','HelpFiles',str(num), - string.join(self.userHelpList[num-1][:2],';')) + ';'.join(self.userHelpList[num-1][:2])) def LoadFontCfg(self): ##base editor font selection list diff --git a/Lib/idlelib/configHandler.py b/Lib/idlelib/configHandler.py index 0a08de2491f..963cf951782 100644 --- a/Lib/idlelib/configHandler.py +++ b/Lib/idlelib/configHandler.py @@ -19,7 +19,6 @@ configuration problem notification and resolution. """ import os import sys -import string import macosxSupport from ConfigParser import ConfigParser, NoOptionError, NoSectionError @@ -632,7 +631,7 @@ class IdleConf: menuItem='' #make these empty helpPath='' #so value won't be added to list else: #config entry contains ';' as expected - value=string.split(value,';') + value=value.split(';') menuItem=value[0].strip() helpPath=value[1].strip() if menuItem and helpPath: #neither are empty strings diff --git a/Lib/idlelib/keybindingDialog.py b/Lib/idlelib/keybindingDialog.py index 69900f9fbd8..16db5576f2d 100644 --- a/Lib/idlelib/keybindingDialog.py +++ b/Lib/idlelib/keybindingDialog.py @@ -163,7 +163,7 @@ class GetKeysDialog(Toplevel): if finalKey: finalKey = self.TranslateKey(finalKey, modifiers) keyList.append(finalKey) - self.keyString.set('<' + string.join(keyList,'-') + '>') + self.keyString.set('<' + '-'.join(keyList) + '>') def GetModifiers(self): modList = [variable.get() for variable in self.modifier_vars] diff --git a/Lib/inspect.py b/Lib/inspect.py index 6ebd445dbc2..d4cfc0714a6 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -29,7 +29,7 @@ Here are some of the useful functions provided by this module: __author__ = 'Ka-Ping Yee ' __date__ = '1 Jan 2001' -import sys, os, types, string, re, dis, imp, tokenize, linecache +import sys, os, types, re, dis, imp, tokenize, linecache from operator import attrgetter # ----------------------------------------------------------- type-checking @@ -301,8 +301,8 @@ def getmro(cls): # -------------------------------------------------- source code extraction def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" - expline = string.expandtabs(line) - return len(expline) - len(string.lstrip(expline)) + expline = line.expandtabs() + return len(expline) - len(expline.lstrip()) def getdoc(object): """Get the documentation string for an object. @@ -317,14 +317,14 @@ def getdoc(object): if not isinstance(doc, types.StringTypes): return None try: - lines = string.split(string.expandtabs(doc), '\n') + lines = doc.expandtabs().split('\n') except UnicodeError: return None else: # Find minimum indentation of any non-blank lines after first line. margin = sys.maxint for line in lines[1:]: - content = len(string.lstrip(line)) + content = len(line.lstrip()) if content: indent = len(line) - content margin = min(margin, indent) @@ -338,7 +338,7 @@ def getdoc(object): lines.pop() while lines and not lines[0]: lines.pop(0) - return string.join(lines, '\n') + return '\n'.join(lines) def getfile(object): """Work out which source or compiled file an object was defined in.""" @@ -382,10 +382,10 @@ def getmodulename(path): def getsourcefile(object): """Return the Python source file an object was defined in, if it exists.""" filename = getfile(object) - if string.lower(filename[-4:]) in ('.pyc', '.pyo'): + if filename[-4:].lower() in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' for suffix, mode, kind in imp.get_suffixes(): - if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: + if 'b' in mode and filename[-len(suffix):].lower() == suffix: # Looks like a binary file. We want to only return a text file. return None if os.path.exists(filename): @@ -527,36 +527,36 @@ def getcomments(object): # Look for a comment block at the top of the file. start = 0 if lines and lines[0][:2] == '#!': start = 1 - while start < len(lines) and string.strip(lines[start]) in ('', '#'): + while start < len(lines) and lines[start].strip() in ('', '#'): start = start + 1 if start < len(lines) and lines[start][:1] == '#': comments = [] end = start while end < len(lines) and lines[end][:1] == '#': - comments.append(string.expandtabs(lines[end])) + comments.append(lines[end].expandtabs()) end = end + 1 - return string.join(comments, '') + return ''.join(comments) # Look for a preceding block of comments at the same indentation. elif lnum > 0: indent = indentsize(lines[lnum]) end = lnum - 1 - if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \ + if end >= 0 and lines[end].lstrip()[:1] == '#' and \ indentsize(lines[end]) == indent: - comments = [string.lstrip(string.expandtabs(lines[end]))] + comments = [lines[end].expandtabs().lstrip()] if end > 0: end = end - 1 - comment = string.lstrip(string.expandtabs(lines[end])) + comment = lines[end].expandtabs().lstrip() while comment[:1] == '#' and indentsize(lines[end]) == indent: comments[:0] = [comment] end = end - 1 if end < 0: break - comment = string.lstrip(string.expandtabs(lines[end])) - while comments and string.strip(comments[0]) == '#': + comment = lines[end].expandtabs().lstrip() + while comments and comments[0].strip() == '#': comments[:1] = [] - while comments and string.strip(comments[-1]) == '#': + while comments and comments[-1].strip() == '#': comments[-1:] = [] - return string.join(comments, '') + return ''.join(comments) class EndOfBlock(Exception): pass @@ -628,7 +628,7 @@ def getsource(object): or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = getsourcelines(object) - return string.join(lines, '') + return ''.join(lines) # --------------------------------------------------- class tree extraction def walktree(classes, children, parent): @@ -801,7 +801,7 @@ def joinseq(seq): if len(seq) == 1: return '(' + seq[0] + ',)' else: - return '(' + string.join(seq, ', ') + ')' + return '(' + ', '.join(seq) + ')' def strseq(object, convert, join=joinseq): """Recursively walk a sequence, stringifying each element.""" @@ -866,7 +866,7 @@ def formatargspec(args, varargs=None, varkw=None, defaults=None, specs.append(spec) if varkw is not None: specs.append(formatvarkw(formatargandannotation(varkw))) - result = '(' + string.join(specs, ', ') + ')' + result = '(' + ', '.join(specs) + ')' if 'return' in annotations: result += formatreturns(formatannotation(annotations['return'])) return result @@ -893,7 +893,7 @@ def formatargvalues(args, varargs, varkw, locals, specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) - return '(' + string.join(specs, ', ') + ')' + return '(' + ', '.join(specs) + ')' # -------------------------------------------------- stack frame extraction def getframeinfo(frame, context=1): diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py index 7ff9f252d01..4eb03929307 100644 --- a/Lib/logging/__init__.py +++ b/Lib/logging/__init__.py @@ -26,7 +26,7 @@ Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ -import sys, os, types, time, string, cStringIO, traceback +import sys, os, types, time, cStringIO, traceback try: import codecs @@ -54,7 +54,7 @@ __date__ = "16 February 2007" # if hasattr(sys, 'frozen'): #support for py2exe _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:]) -elif string.lower(__file__[-4:]) in ['.pyc', '.pyo']: +elif __file__[-4:].lower() in ['.pyc', '.pyo']: _srcfile = __file__[:-4] + '.py' else: _srcfile = __file__ @@ -416,7 +416,7 @@ class Formatter: formatException() and appended to the message. """ record.message = record.getMessage() - if string.find(self._fmt,"%(asctime)") >= 0: + if self._fmt.find("%(asctime)") >= 0: record.asctime = self.formatTime(record, self.datefmt) s = self._fmt % record.__dict__ if record.exc_info: @@ -510,7 +510,7 @@ class Filter: return 1 elif self.name == record.name: return 1 - elif string.find(record.name, self.name, 0, self.nlen) != 0: + elif record.name.find(self.name, 0, self.nlen) != 0: return 0 return (record.name[self.nlen] == ".") @@ -896,7 +896,7 @@ class Manager: from the specified logger to the root of the logger hierarchy. """ name = alogger.name - i = string.rfind(name, ".") + i = name.rfind(".") rv = None while (i > 0) and not rv: substr = name[:i] @@ -909,7 +909,7 @@ class Manager: else: assert isinstance(obj, PlaceHolder) obj.append(alogger) - i = string.rfind(name, ".", 0, i - 1) + i = name.rfind(".", 0, i - 1) if not rv: rv = self.root alogger.parent = rv diff --git a/Lib/logging/config.py b/Lib/logging/config.py index 2888e5ee80d..8b281532c59 100644 --- a/Lib/logging/config.py +++ b/Lib/logging/config.py @@ -27,7 +27,7 @@ Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ -import sys, logging, logging.handlers, string, socket, struct, os, traceback, types +import sys, logging, logging.handlers, socket, struct, os, traceback, types try: import thread @@ -89,7 +89,7 @@ def fileConfig(fname, defaults=None): def _resolve(name): """Resolve a dotted name to a global object.""" - name = string.split(name, '.') + name = name.split('.') used = name.pop(0) found = __import__(used) for n in name: @@ -107,10 +107,10 @@ def _create_formatters(cp): flist = cp.get("formatters", "keys") if not len(flist): return {} - flist = string.split(flist, ",") + flist = flist.split(",") formatters = {} for form in flist: - sectname = "formatter_%s" % string.strip(form) + sectname = "formatter_%s" % form.strip() opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) @@ -135,11 +135,11 @@ def _install_handlers(cp, formatters): hlist = cp.get("handlers", "keys") if not len(hlist): return {} - hlist = string.split(hlist, ",") + hlist = hlist.split(",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: - sectname = "handler_%s" % string.strip(hand) + sectname = "handler_%s" % hand.strip() klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: @@ -175,8 +175,8 @@ def _install_loggers(cp, handlers): # configure the root first llist = cp.get("loggers", "keys") - llist = string.split(llist, ",") - llist = map(lambda x: string.strip(x), llist) + llist = llist.split(",") + llist = map(lambda x: x.strip(), llist) llist.remove("root") sectname = "logger_root" root = logging.root @@ -189,9 +189,9 @@ def _install_loggers(cp, handlers): root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): - hlist = string.split(hlist, ",") + hlist = hlist.split(",") for hand in hlist: - log.addHandler(handlers[string.strip(hand)]) + log.addHandler(handlers[hand.strip()]) #and now the others... #we don't want to lose the existing loggers, @@ -224,9 +224,9 @@ def _install_loggers(cp, handlers): logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): - hlist = string.split(hlist, ",") + hlist = hlist.split(",") for hand in hlist: - logger.addHandler(handlers[string.strip(hand)]) + logger.addHandler(handlers[hand.strip()]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references diff --git a/Lib/logging/handlers.py b/Lib/logging/handlers.py index 687ecfe05c6..83bf3e32032 100644 --- a/Lib/logging/handlers.py +++ b/Lib/logging/handlers.py @@ -27,7 +27,7 @@ Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ -import sys, logging, socket, types, os, string, struct, time, glob +import sys, logging, socket, types, os, struct, time, glob try: import cPickle as pickle except ImportError: @@ -162,7 +162,7 @@ class TimedRotatingFileHandler(BaseRotatingHandler): """ def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None): BaseRotatingHandler.__init__(self, filename, 'a', encoding) - self.when = string.upper(when) + self.when = when.upper() self.backupCount = backupCount # Calculate the real rollover interval, which is just the number of # seconds between rollovers. Also set the filename suffix used when @@ -792,7 +792,7 @@ class SMTPHandler(logging.Handler): msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, - string.join(self.toaddrs, ","), + ",".join(self.toaddrs), self.getSubject(record), formatdate(), msg) smtp.sendmail(self.fromaddr, self.toaddrs, msg) @@ -913,7 +913,7 @@ class HTTPHandler(logging.Handler): ("GET" or "POST") """ logging.Handler.__init__(self) - method = string.upper(method) + method = method.upper() if method not in ["GET", "POST"]: raise ValueError, "method must be GET or POST" self.host = host @@ -941,7 +941,7 @@ class HTTPHandler(logging.Handler): url = self.url data = urllib.urlencode(self.mapLogRecord(record)) if self.method == "GET": - if (string.find(url, '?') >= 0): + if (url.find('?') >= 0): sep = '&' else: sep = '?' @@ -949,7 +949,7 @@ class HTTPHandler(logging.Handler): 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, ":") + i = host.find(":") if i >= 0: host = host[:i] h.putheader("Host", host) diff --git a/Lib/plat-irix6/cddb.py b/Lib/plat-irix6/cddb.py index bfdf57da84b..bdd2ec348c3 100644 --- a/Lib/plat-irix6/cddb.py +++ b/Lib/plat-irix6/cddb.py @@ -14,14 +14,14 @@ # You can then use c.write() to write out the changed values to the # .cdplayerrc file. -import string, posix, os +import posix, os _cddbrc = '.cddb' _DB_ID_NTRACKS = 5 _dbid_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@_=+abcdefghijklmnopqrstuvwxyz' def _dbid(v): if v >= len(_dbid_map): - return string.zfill(v, 2) + return v.zfill(2) else: return _dbid_map[v] @@ -164,11 +164,10 @@ class Cddb: for i in range(nidtracks): start, length = tracklist[i] self.id = self.id + _dbid(length[0]) + _dbid(length[1]) - self.toc = string.zfill(ntracks, 2) + self.toc = ntracks.zfill(2) for track in tracklist: start, length = track - self.toc = self.toc + string.zfill(length[0], 2) + \ - string.zfill(length[1], 2) + self.toc = self.toc + length[0].zfill(2) + length[1].zfill(2) def write(self): import posixpath diff --git a/Lib/plat-irix6/cdplayer.py b/Lib/plat-irix6/cdplayer.py index a2be8b44f18..493527faa40 100644 --- a/Lib/plat-irix6/cdplayer.py +++ b/Lib/plat-irix6/cdplayer.py @@ -18,7 +18,6 @@ cdplayerrc = '.cdplayerrc' class Cdplayer: def __init__(self, tracklist): - import string self.artist = '' self.title = '' if type(tracklist) == type(''): @@ -29,11 +28,11 @@ class Cdplayer: int(tracklist[i+2:i+4])))) tracklist = t self.track = [None] + [''] * len(tracklist) - self.id = 'd' + string.zfill(len(tracklist), 2) + self.id = 'd' + repr(len(tracklist)).zfill(2) for track in tracklist: start, length = track - self.id = self.id + string.zfill(length[0], 2) + \ - string.zfill(length[1], 2) + self.id = self.id + repr(length[0]).zfill(2) + \ + repr(length[1]).zfill(2) try: import posix f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r') diff --git a/Lib/plat-mac/EasyDialogs.py b/Lib/plat-mac/EasyDialogs.py index 3c920119e2e..1bca4cdb1e1 100644 --- a/Lib/plat-mac/EasyDialogs.py +++ b/Lib/plat-mac/EasyDialogs.py @@ -30,7 +30,6 @@ from Carbon import Menu from Carbon import AE import Nav import MacOS -import string from Carbon.ControlAccessor import * # Also import Controls constants import Carbon.File import macresource @@ -54,12 +53,12 @@ def _interact(): def cr2lf(text): if '\r' in text: - text = string.join(string.split(text, '\r'), '\n') + text = '\n'.join(text.split('\r')) return text def lf2cr(text): if '\n' in text: - text = string.join(string.split(text, '\n'), '\r') + text = '\r'.join(text.split('\n')) if len(text) > 253: text = text[:253] + '\311' return text @@ -543,7 +542,7 @@ def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfo d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff) h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA) oldstr = GetDialogItemText(h) - tmplist = string.split(oldstr) + tmplist = oldstr.split() newlist = [] while tmplist: item = tmplist[0] diff --git a/Lib/plat-mac/aepack.py b/Lib/plat-mac/aepack.py index aa1734d27c1..9be242cf9d7 100644 --- a/Lib/plat-mac/aepack.py +++ b/Lib/plat-mac/aepack.py @@ -13,9 +13,7 @@ coerce(x, wanted_sample) coerces a python object to another python object # import struct -import string import types -from string import strip from types import * from Carbon import AE from Carbon.AppleEvents import * diff --git a/Lib/plat-mac/aetypes.py b/Lib/plat-mac/aetypes.py index 9dfb39fed3a..9b739f6d329 100644 --- a/Lib/plat-mac/aetypes.py +++ b/Lib/plat-mac/aetypes.py @@ -3,7 +3,6 @@ from Carbon.AppleEvents import * import struct from types import * -import string # # convoluted, since there are cyclic dependencies between this file and @@ -41,7 +40,7 @@ class Enum: return "Enum(%r)" % (self.enum,) def __str__(self): - return string.strip(self.enum) + return self.enum.strip() def __aepack__(self): return pack(self.enum, typeEnumeration) @@ -108,7 +107,7 @@ class Type: return "Type(%r)" % (self.type,) def __str__(self): - return string.strip(self.type) + return self.type.strip() def __aepack__(self): return pack(self.type, typeType) @@ -131,7 +130,7 @@ class Keyword: return "Keyword(%r)" % self.keyword def __str__(self): - return string.strip(self.keyword) + return self.keyword.strip() def __aepack__(self): return pack(self.keyword, typeKeyword) @@ -170,7 +169,7 @@ class Comparison: return "Comparison(%r, %r, %r)" % (self.obj1, self.relo, self.obj2) def __str__(self): - return "%s %s %s" % (nice(self.obj1), string.strip(self.relo), nice(self.obj2)) + return "%s %s %s" % (nice(self.obj1), self.relo.strip(), nice(self.obj2)) def __aepack__(self): return pack({'obj1': self.obj1, @@ -198,7 +197,7 @@ class Ordinal: return "Ordinal(%r)" % (self.abso,) def __str__(self): - return "%s" % (string.strip(self.abso)) + return "%s" % (self.abso.strip()) def __aepack__(self): return pack(self.abso, 'abso') @@ -225,10 +224,10 @@ class Logical: def __str__(self): if type(self.term) == ListType and len(self.term) == 2: return "%s %s %s" % (nice(self.term[0]), - string.strip(self.logc), + self.logc.strip(), nice(self.term[1])) else: - return "%s(%s)" % (string.strip(self.logc), nice(self.term)) + return "%s(%s)" % (self.logc.strip(), nice(self.term)) def __aepack__(self): return pack({'logc': mkenum(self.logc), 'term': self.term}, 'logi') diff --git a/Lib/plat-mac/buildtools.py b/Lib/plat-mac/buildtools.py index 4a0efbfb354..d2b53b35330 100644 --- a/Lib/plat-mac/buildtools.py +++ b/Lib/plat-mac/buildtools.py @@ -2,7 +2,6 @@ import sys import os -import string import imp import marshal from Carbon import Res @@ -86,7 +85,7 @@ def process(template, filename, destname, copy_codefragment=0, # Set the destination file name. Note that basename # does contain the whole filepath, only a .py is stripped. - if string.lower(filename[-3:]) == ".py": + if filename[-3:].lower() == ".py": basename = filename[:-3] if MacOS.runtimemodel != 'macho' and not destname: destname = basename @@ -347,7 +346,7 @@ def copyres(input, output, skiptypes, skipowner, progress=None): for ires in range(1, 1+nresources): res = Res.Get1IndResource(type, ires) id, type, name = res.GetResInfo() - lcname = string.lower(name) + lcname = name.lower() if lcname == OWNERNAME and id == 0: if skipowner: diff --git a/Lib/plat-mac/gensuitemodule.py b/Lib/plat-mac/gensuitemodule.py index fd706a0cdab..6d1ceae268a 100644 --- a/Lib/plat-mac/gensuitemodule.py +++ b/Lib/plat-mac/gensuitemodule.py @@ -698,7 +698,7 @@ class SuiteCompiler: """Generate class boilerplate""" classname = '%s_Events'%self.modname if self.basemodule: - modshortname = string.split(self.basemodule.__name__, '.')[-1] + modshortname = self.basemodule.__name__.split('.')[-1] baseclassname = '%s_Events'%modshortname self.fp.write("class %s(%s):\n\n"%(classname, baseclassname)) else: @@ -1169,7 +1169,7 @@ def compiledataflags(flags): bits.append(dataflagdict[i]) else: bits.append(repr(i)) - return '[%s]' % string.join(bits) + return '[%s]' % ' '.join(bits) def ascii(str): """Return a string with all non-ascii characters hex-encoded""" diff --git a/Lib/plat-mac/ic.py b/Lib/plat-mac/ic.py index 5c109d6cf11..769400ae8ea 100644 --- a/Lib/plat-mac/ic.py +++ b/Lib/plat-mac/ic.py @@ -1,7 +1,6 @@ """IC wrapper module, based on Internet Config 1.3""" import icglue -import string import sys import os from Carbon import Res @@ -135,7 +134,7 @@ _decoder_table = { def _decode(data, key): if '\245' in key: - key2 = key[:string.index(key, '\245')+1] + key2 = key[:key.index('\245')+1] else: key2 = key if key2 in _decoder_table: @@ -148,7 +147,7 @@ def _code(data, key): if type(data) == _ICOpaqueDataType: return data.data if '\245' in key: - key2 = key[:string.index(key, '\245')+1] + key2 = key[:key.index('\245')+1] else: key2 = key if key2 in _decoder_table: diff --git a/Lib/plat-riscos/riscospath.py b/Lib/plat-riscos/riscospath.py index ea39e60f103..af89eb3d6cb 100644 --- a/Lib/plat-riscos/riscospath.py +++ b/Lib/plat-riscos/riscospath.py @@ -59,13 +59,13 @@ def _split(p): """ dash= _allowMOSFSNames and p[:1]=='-' if dash: - q= string.find(p, '-', 1)+1 + q= p.find('-', 1)+1 else: if p[:1]==':': q= 0 else: - q= string.find(p, ':')+1 # q= index of start of non-FS portion of path - s= string.find(p, '#') + q= p.find(':')+1 # q= index of start of non-FS portion of path + s= p.find('#') if s==-1 or s>q: s= q # find end of main FS name, not including special field else: @@ -75,7 +75,7 @@ def _split(p): break # disallow invalid non-special-field characters in FS name r= q if p[q:q+1]==':': - r= string.find(p, '.', q+1)+1 + r= p.find('.', q+1)+1 if r==0: r= len(p) # find end of drive name (if any) following FS name (if any) return (p[:q], p[q:r], p[r:]) @@ -87,7 +87,7 @@ def normcase(p): OS filesystems are case-insensitive. However, not all filesystems have to be, and there's no simple way to find out what type an FS is argh. """ - return string.lower(p) + return p.lower() def isabs(p): @@ -126,7 +126,7 @@ def split(p): name must still be dealt with separately since special field may contain '.'. """ (fs, drive, path)= _split(p) - q= string.rfind(path, '.') + q= path.rfind('.') if q!=-1: return (fs+drive+path[:q], path[q+1:]) return ('', p) @@ -139,7 +139,7 @@ def splitext(p): """ (tail, head)= split(p) if '/' in head: - q= len(head)-string.rfind(head, '/') + q= len(head)-head.rfind('/') return (p[:-q], p[-q:]) return (p, '') @@ -291,7 +291,7 @@ def expanduser(p): fsname= fs[1:-1] else: fsname= fs[:-1] - fsname= string.split(fsname, '#', 1)[0] # remove special field from fs + fsname= fsname.split('#', 1)[0] # remove special field from fs x= swi.swi('OS_FSControl', 'ib2s.i;.....i', 54, b, fsname, l) if x= 2 and pkg[0] == 'OpenLinux': # XXX does Caldera support non Intel platforms ? If yes, # where can we find the needed id ? @@ -258,7 +258,7 @@ def _parse_release_file(firstline): return tuple(m.groups()) # Unkown format... take the first two words - l = string.split(string.strip(firstline)) + l = firstline.strip().split() if l: version = l[0] if len(l) > 1: @@ -451,7 +451,7 @@ def _norm_version(version, build=''): """ Normalize the version and build strings and return a single version string using the format major.minor.build (or patchlevel). """ - l = string.split(version,'.') + l = version.split('.') if build: l.append(build) try: @@ -460,7 +460,7 @@ def _norm_version(version, build=''): strings = l else: strings = map(str,ints) - version = string.join(strings[:3],'.') + version = '.'.join(strings[:3]) return version _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) ' @@ -505,7 +505,7 @@ def _syscmd_ver(system='', release='', version='', return system,release,version # Parse the output - info = string.strip(info) + info = info.strip() m = _ver_output.match(info) if m is not None: system,release,version = m.groups() @@ -766,7 +766,7 @@ def system_alias(system,release,version): # These releases use the old name SunOS return system,release,version # Modify release (marketing release = SunOS release - 3) - l = string.split(release,'.') + l = release.split('.') if l: try: major = int(l[0]) @@ -775,7 +775,7 @@ def system_alias(system,release,version): else: major = major - 3 l[0] = str(major) - release = string.join(l,'.') + release = '.'.join(l) if release < '6': system = 'Solaris' else: @@ -806,28 +806,24 @@ def _platform(*args): compatible format e.g. "system-version-machine". """ # Format the platform string - platform = string.join( - map(string.strip, - filter(len, args)), - '-') + platform = '-'.join(x.strip() for x in filter(len, args)) # Cleanup some possible filename obstacles... - replace = string.replace - platform = replace(platform,' ','_') - platform = replace(platform,'/','-') - platform = replace(platform,'\\','-') - platform = replace(platform,':','-') - platform = replace(platform,';','-') - platform = replace(platform,'"','-') - platform = replace(platform,'(','-') - platform = replace(platform,')','-') + platform = platform.replace(' ','_') + platform = platform.replace('/','-') + platform = platform.replace('\\','-') + platform = platform.replace(':','-') + platform = platform.replace(';','-') + platform = platform.replace('"','-') + platform = platform.replace('(','-') + platform = platform.replace(')','-') # No need to report 'unknown' information... - platform = replace(platform,'unknown','') + platform = platform.replace('unknown','') # Fold '--'s and remove trailing '-' while 1: - cleaned = replace(platform,'--','-') + cleaned = platform.replace('--','-') if cleaned == platform: break platform = cleaned @@ -889,7 +885,7 @@ def _syscmd_uname(option,default=''): f = os.popen('uname %s 2> /dev/null' % option) except (AttributeError,os.error): return default - output = string.strip(f.read()) + output = f.read().strip() rc = f.close() if not output or rc: return default @@ -911,7 +907,7 @@ def _syscmd_file(target,default=''): f = os.popen('file %s 2> /dev/null' % target) except (AttributeError,os.error): return default - output = string.strip(f.read()) + output = f.read().strip() rc = f.close() if not output or rc: return default @@ -1082,7 +1078,7 @@ def uname(): elif system[:4] == 'java': release,vendor,vminfo,osinfo = java_ver() system = 'Java' - version = string.join(vminfo,', ') + version = ', '.join(vminfo) if not version: version = vendor @@ -1285,10 +1281,10 @@ def _sys_version(sys_version=None): builddate = builddate + ' ' + buildtime # Add the patchlevel version if missing - l = string.split(version, '.') + l = version.split('.') if len(l) == 2: l.append('0') - version = string.join(l, '.') + version = '.'.join(l) # Build and cache the result result = (name, version, branch, revision, buildno, builddate, compiler) @@ -1345,7 +1341,7 @@ def python_version_tuple(): """ if hasattr(sys, 'version_info'): return sys.version_info[:3] - return tuple(string.split(_sys_version()[1], '.')) + return tuple(_sys_version()[1].split('.')) def python_branch(): diff --git a/Lib/pydoc.py b/Lib/pydoc.py index 9fca8c268b2..59c4593bd10 100755 --- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -54,7 +54,6 @@ Richard Chamberlain, for the first implementation of textdoc. import sys, imp, os, re, types, inspect, __builtin__, pkgutil from repr import Repr -from string import expandtabs, find, join, lower, split, strip, rfind, rstrip try: from collections import deque except ImportError: @@ -80,16 +79,16 @@ def pathdirs(): def getdoc(object): """Get the doc string or comments for an object.""" result = inspect.getdoc(object) or inspect.getcomments(object) - return result and re.sub('^ *\n', '', rstrip(result)) or '' + return result and re.sub('^ *\n', '', result.rstrip()) or '' def splitdoc(doc): """Split a doc string into a synopsis line (if any) and the rest.""" - lines = split(strip(doc), '\n') + lines = doc.strip().split('\n') if len(lines) == 1: return lines[0], '' - elif len(lines) >= 2 and not rstrip(lines[1]): - return lines[0], join(lines[2:], '\n') - return '', join(lines, '\n') + elif len(lines) >= 2 and not lines[1].rstrip(): + return lines[0], '\n'.join(lines[2:]) + return '', '\n'.join(lines) def classname(object, modname): """Get a class name and qualify it with a module name if necessary.""" @@ -107,7 +106,7 @@ def isdata(object): def replace(text, *pairs): """Do a series of global replacements on a string.""" while pairs: - text = join(split(text, pairs[0]), pairs[1]) + text = pairs[1].join(text.split(pairs[0])) pairs = pairs[2:] return text @@ -190,18 +189,18 @@ def ispackage(path): def source_synopsis(file): line = file.readline() - while line[:1] == '#' or not strip(line): + while line[:1] == '#' or not line.strip(): line = file.readline() if not line: break - line = strip(line) + line = line.strip() if line[:4] == 'r"""': line = line[1:] if line[:3] == '"""': line = line[3:] if line[-1:] == '\\': line = line[:-1] - while not strip(line): + while not line.strip(): line = file.readline() if not line: break - result = strip(split(line, '"""')[0]) + result = line.split('"""')[0].strip() else: result = None return result @@ -297,13 +296,13 @@ def safeimport(path, forceload=0, cache={}): # A SyntaxError occurred before we could execute the module. raise ErrorDuringImport(value.filename, info) elif exc is ImportError and \ - split(lower(str(value)))[:2] == ['no', 'module']: + str(value).lower().split()[:2] == ['no', 'module']: # The module was not found. return None else: # Some other error occurred during the importing process. raise ErrorDuringImport(path, sys.exc_info()) - for part in split(path, '.')[1:]: + for part in path.split('.')[1:]: try: module = getattr(module, part) except AttributeError: return None return module @@ -382,7 +381,7 @@ class HTMLRepr(Repr): def repr1(self, x, level): if hasattr(type(x), '__name__'): - methodname = 'repr_' + join(split(type(x).__name__), '_') + methodname = 'repr_' + '_'.join(type(x).__name__.split()) if hasattr(self, methodname): return getattr(self, methodname)(x, level) return self.escape(cram(stripid(repr(x)), self.maxother)) @@ -466,7 +465,7 @@ class HTMLDoc(Doc): def preformat(self, text): """Format literal preformatted text.""" - text = self.escape(expandtabs(text)) + text = self.escape(text.expandtabs()) return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', ' ', ' ', '\n', '
\n') @@ -551,7 +550,7 @@ class HTMLDoc(Doc): results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) - return join(results, '') + return ''.join(results) # ---------------------------------------------- type-specific routines @@ -567,7 +566,7 @@ class HTMLDoc(Doc): parents = [] for base in bases: parents.append(self.classlink(base, modname)) - result = result + '(' + join(parents, ', ') + ')' + result = result + '(' + ', '.join(parents) + ')' result = result + '\n' elif type(entry) is type([]): result = result + '
\n%s
\n' % self.formattree( @@ -581,13 +580,13 @@ class HTMLDoc(Doc): all = object.__all__ except AttributeError: all = None - parts = split(name, '.') + parts = name.split('.') links = [] for i in range(len(parts)-1): links.append( '%s' % - (join(parts[:i+1], '.'), parts[i])) - linkedname = join(links + parts[-1:], '.') + ('.'.join(parts[:i+1]), parts[i])) + linkedname = '.'.join(links + parts[-1:]) head = '%s' % linkedname try: path = inspect.getabsfile(object) @@ -602,12 +601,12 @@ class HTMLDoc(Doc): if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': - version = strip(version[11:-1]) + version = version[11:-1].strip() info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: - head = head + ' (%s)' % join(info, ', ') + head = head + ' (%s)' % ', '.join(info) docloc = self.getdocloc(object) if docloc is not None: docloc = '
Module Docs' % locals() @@ -674,19 +673,19 @@ class HTMLDoc(Doc): for key, value in classes: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( - 'Classes', '#ffffff', '#ee77aa', join(contents)) + 'Classes', '#ffffff', '#ee77aa', ' '.join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( - 'Functions', '#ffffff', '#eeaa77', join(contents)) + 'Functions', '#ffffff', '#eeaa77', ' '.join(contents)) if data: contents = [] for key, value in data: contents.append(self.document(value, key)) result = result + self.bigsection( - 'Data', '#ffffff', '#55aa55', join(contents, '
\n')) + 'Data', '#ffffff', '#55aa55', '
\n'.join(contents)) if hasattr(object, '__author__'): contents = self.markup(str(object.__author__), self.preformat) result = result + self.bigsection( @@ -831,7 +830,7 @@ class HTMLDoc(Doc): parents = [] for base in bases: parents.append(self.classlink(base, object.__module__)) - title = title + '(%s)' % join(parents, ', ') + title = title + '(%s)' % ', '.join(parents) doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) doc = doc and '%s
 
' % doc @@ -951,7 +950,7 @@ class TextRepr(Repr): def repr1(self, x, level): if hasattr(type(x), '__name__'): - methodname = 'repr_' + join(split(type(x).__name__), '_') + methodname = 'repr_' + '_'.join(type(x).__name__.split()) if hasattr(self, methodname): return getattr(self, methodname)(x, level) return cram(stripid(repr(x)), self.maxother) @@ -983,19 +982,20 @@ class TextDoc(Doc): def bold(self, text): """Format a string in bold by overstriking.""" - return join(map(lambda ch: ch + '\b' + ch, text), '') + return ''.join(map(lambda ch: ch + '\b' + ch, text)) def indent(self, text, prefix=' '): """Indent text by prepending a given prefix to each line.""" if not text: return '' - lines = split(text, '\n') + lines = text.split('\n') lines = map(lambda line, prefix=prefix: prefix + line, lines) - if lines: lines[-1] = rstrip(lines[-1]) - return join(lines, '\n') + if lines: lines[-1] = lines[-1].rstrip() + return '\n'.join(lines) def section(self, title, contents): """Format a section with a given heading.""" - return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n' + clean_contents = self.indent(contents).rstrip() + return self.bold(title) + '\n' + clean_contents + '\n\n' # ---------------------------------------------- type-specific routines @@ -1008,7 +1008,7 @@ class TextDoc(Doc): result = result + prefix + classname(c, modname) if bases and bases != (parent,): parents = map(lambda c, m=modname: classname(c, m), bases) - result = result + '(%s)' % join(parents, ', ') + result = result + '(%s)' % ', '.join(parents) result = result + '\n' elif type(entry) is type([]): result = result + self.formattree( @@ -1068,7 +1068,7 @@ class TextDoc(Doc): modpkgs.sort() result = result + self.section( - 'PACKAGE CONTENTS', join(modpkgs, '\n')) + 'PACKAGE CONTENTS', '\n'.join(modpkgs)) if classes: classlist = map(lambda (key, value): value, classes) @@ -1076,24 +1076,24 @@ class TextDoc(Doc): inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name)) - result = result + self.section('CLASSES', join(contents, '\n')) + result = result + self.section('CLASSES', '\n'.join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name)) - result = result + self.section('FUNCTIONS', join(contents, '\n')) + result = result + self.section('FUNCTIONS', '\n'.join(contents)) if data: contents = [] for key, value in data: contents.append(self.docother(value, key, name, maxlen=70)) - result = result + self.section('DATA', join(contents, '\n')) + result = result + self.section('DATA', '\n'.join(contents)) if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': - version = strip(version[11:-1]) + version = version[11:-1].strip() result = result + self.section('VERSION', version) if hasattr(object, '__date__'): result = result + self.section('DATE', str(object.__date__)) @@ -1118,7 +1118,7 @@ class TextDoc(Doc): title = self.bold(name) + ' = class ' + realname if bases: parents = map(makename, bases) - title = title + '(%s)' % join(parents, ', ') + title = title + '(%s)' % ', '.join(parents) doc = getdoc(object) contents = doc and [doc + '\n'] or [] @@ -1214,7 +1214,7 @@ class TextDoc(Doc): contents = '\n'.join(contents) if not contents: return title + '\n' - return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n' + return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n' def formatvalue(self, object): """Format an argument default value as text.""" @@ -1267,7 +1267,7 @@ class TextDoc(Doc): return decl + '\n' else: doc = getdoc(object) or '' - return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n') + return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n') def _docdescriptor(self, name, value, mod): results = [] @@ -1368,7 +1368,7 @@ def tempfilepager(text, cmd): def ttypager(text): """Page through text on a text terminal.""" - lines = split(plain(text), '\n') + lines = plain(text).split('\n') try: import tty fd = sys.stdin.fileno() @@ -1381,7 +1381,7 @@ def ttypager(text): try: r = inc = os.environ.get('LINES', 25) - 1 - sys.stdout.write(join(lines[:inc], '\n') + '\n') + sys.stdout.write('\n'.join(lines[:inc]) + '\n') while lines[r:]: sys.stdout.write('-- more --') sys.stdout.flush() @@ -1397,7 +1397,7 @@ def ttypager(text): if c in ('b', 'B', '\x1b'): r = r - inc - inc if r < 0: r = 0 - sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n') + sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n') r = r + inc finally: @@ -1437,10 +1437,10 @@ def describe(thing): def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" - parts = [part for part in split(path, '.') if part] + parts = [part for part in path.split('.') if part] module, n = None, 0 while n < len(parts): - nextmodule = safeimport(join(parts[:n+1], '.'), forceload) + nextmodule = safeimport('.'.join(parts[:n+1]), forceload) if nextmodule: module, n = nextmodule, n + 1 else: break if module: @@ -1637,8 +1637,8 @@ class Helper: for dir in [os.environ.get('PYTHONDOCS'), homedir and os.path.join(homedir, 'doc'), os.path.join(execdir, 'doc'), - '/usr/doc/python-docs-' + split(sys.version)[0], - '/usr/doc/python-' + split(sys.version)[0], + '/usr/doc/python-docs-' + sys.version.split()[0], + '/usr/doc/python-' + sys.version.split()[0], '/usr/doc/python-docs-' + sys.version[:3], '/usr/doc/python-' + sys.version[:3], os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]: @@ -1672,8 +1672,8 @@ has the same effect as typing a particular string at the help> prompt. if not request: break except (KeyboardInterrupt, EOFError): break - request = strip(replace(request, '"', '', "'", '')) - if lower(request) in ('q', 'quit'): break + request = replace(request, '"', '', "'", '').strip() + if request.lower() in ('q', 'quit'): break self.help(request) def getline(self, prompt): @@ -1692,7 +1692,7 @@ has the same effect as typing a particular string at the help> prompt. elif request == 'topics': self.listtopics() elif request == 'modules': self.listmodules() elif request[:8] == 'modules ': - self.listmodules(split(request)[1]) + self.listmodules(request.split()[1]) elif request in self.keywords: self.showtopic(request) elif request in self.topics: self.showtopic(request) elif request: doc(request, 'Help on %s:') @@ -1786,11 +1786,11 @@ running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory. parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t') parser.feed(document) buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n ') - pager(' ' + strip(buffer) + '\n') + pager(' ' + buffer.strip() + '\n') if xrefs: buffer = StringIO.StringIO() formatter.DumbWriter(buffer).send_flowing_data( - 'Related help topics: ' + join(split(xrefs), ', ') + '\n') + 'Related help topics: ' + ', '.join(xrefs.split()) + '\n') self.output.write('\n%s\n' % buffer.getvalue()) def listmodules(self, key=''): @@ -1809,7 +1809,7 @@ Please wait a moment while I gather a list of all available modules... def callback(path, modname, desc, modules=modules): if modname and modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' - if find(modname, '.') < 0: + if modname.find('.') < 0: modules[modname] = 1 ModuleScanner().run(callback) self.list(modules.keys()) @@ -1848,7 +1848,7 @@ class ModuleScanner: """An interruptible scanner that searches module synopses.""" def run(self, callback, key=None, completer=None): - if key: key = lower(key) + if key: key = key.lower() self.quit = False seen = {} @@ -1858,8 +1858,10 @@ class ModuleScanner: if key is None: callback(None, modname, '') else: - desc = split(__import__(modname).__doc__ or '', '\n')[0] - if find(lower(modname + ' - ' + desc), key) >= 0: + name = __import__(modname).__doc__ or '' + desc = name.split('\n')[0] + name = modname + ' - ' + desc + if name.lower().find(key) >= 0: callback(None, modname, desc) for importer, modname, ispkg in pkgutil.walk_packages(): @@ -1882,7 +1884,8 @@ class ModuleScanner: module = loader.load_module(modname) desc = (module.__doc__ or '').splitlines()[0] path = getattr(module,'__file__',None) - if find(lower(modname + ' - ' + desc), key) >= 0: + name = modname + ' - ' + desc + if name.lower().find(key) >= 0: callback(path, modname, desc) if completer: @@ -1953,7 +1956,7 @@ def serve(port, callback=None, completer=None): seen = {} for dir in sys.path: indices.append(html.index(dir, seen)) - contents = heading + join(indices) + '''

+ contents = heading + ' '.join(indices) + '''

pydoc by Ka-Ping Yee <ping@lfw.org>''' self.send_document('Index of Modules', contents) @@ -2135,7 +2138,7 @@ def gui(): def goto(self, event=None): selection = self.result_lst.curselection() if selection: - modname = split(self.result_lst.get(selection[0]))[0] + modname = self.result_lst.get(selection[0]).split()[0] self.open(url=self.server.url + modname + '.html') def collapse(self): @@ -2180,7 +2183,7 @@ def gui(): # -------------------------------------------------- command-line interface def ispath(x): - return isinstance(x, str) and find(x, os.sep) >= 0 + return isinstance(x, str) and x.find(os.sep) >= 0 def cli(): """Command-line interface (looks at sys.argv to decide what to do).""" diff --git a/Lib/string.py b/Lib/string.py index 6aafb65c353..e5b5284572f 100644 --- a/Lib/string.py +++ b/Lib/string.py @@ -1,9 +1,4 @@ -"""A collection of string operations (most are no longer used). - -Warning: most of the code you see here isn't normally used nowadays. -Beginning with Python 1.6, many of these functions are implemented as -methods on the standard string object. They used to be implemented by -a built-in module called strop, but strop is now obsolete itself. +"""A collection of string constants. Public module variables: @@ -202,327 +197,12 @@ class Template(metaclass=_TemplateMetaclass): return self.pattern.sub(convert, self.template) - -#################################################################### -# NOTE: Everything below here is deprecated. Use string methods instead. -# This stuff will go away in Python 3.0. - -# Backward compatible names for exceptions -index_error = ValueError -atoi_error = ValueError -atof_error = ValueError -atol_error = ValueError - -# convert UPPER CASE letters to lower case -def lower(s): - """lower(s) -> string - - Return a copy of the string s converted to lowercase. - - """ - return s.lower() - -# Convert lower case letters to UPPER CASE -def upper(s): - """upper(s) -> string - - Return a copy of the string s converted to uppercase. - - """ - return s.upper() - -# Swap lower case letters and UPPER CASE -def swapcase(s): - """swapcase(s) -> string - - Return a copy of the string s with upper case characters - converted to lowercase and vice versa. - - """ - return s.swapcase() - -# Strip leading and trailing tabs and spaces -def strip(s, chars=None): - """strip(s [,chars]) -> string - - Return a copy of the string s with leading and trailing - whitespace removed. - If chars is given and not None, remove characters in chars instead. - If chars is unicode, S will be converted to unicode before stripping. - - """ - return s.strip(chars) - -# Strip leading tabs and spaces -def lstrip(s, chars=None): - """lstrip(s [,chars]) -> string - - Return a copy of the string s with leading whitespace removed. - If chars is given and not None, remove characters in chars instead. - - """ - return s.lstrip(chars) - -# Strip trailing tabs and spaces -def rstrip(s, chars=None): - """rstrip(s [,chars]) -> string - - Return a copy of the string s with trailing whitespace removed. - If chars is given and not None, remove characters in chars instead. - - """ - return s.rstrip(chars) - - -# Split a string into a list of space/tab-separated words -def split(s, sep=None, maxsplit=-1): - """split(s [,sep [,maxsplit]]) -> list of strings - - Return a list of the words in the string s, using sep as the - delimiter string. If maxsplit is given, splits at no more than - maxsplit places (resulting in at most maxsplit+1 words). If sep - is not specified or is None, any whitespace string is a separator. - - (split and splitfields are synonymous) - - """ - return s.split(sep, maxsplit) -splitfields = split - -# Split a string into a list of space/tab-separated words -def rsplit(s, sep=None, maxsplit=-1): - """rsplit(s [,sep [,maxsplit]]) -> list of strings - - Return a list of the words in the string s, using sep as the - delimiter string, starting at the end of the string and working - to the front. If maxsplit is given, at most maxsplit splits are - done. If sep is not specified or is None, any whitespace string - is a separator. - """ - return s.rsplit(sep, maxsplit) - -# Join fields with optional separator -def join(words, sep = ' '): - """join(list [,sep]) -> string - - Return a string composed of the words in list, with - intervening occurrences of sep. The default separator is a - single space. - - (joinfields and join are synonymous) - - """ - return sep.join(words) -joinfields = join - -# Find substring, raise exception if not found -def index(s, *args): - """index(s, sub [,start [,end]]) -> int - - Like find but raises ValueError when the substring is not found. - - """ - return s.index(*args) - -# Find last substring, raise exception if not found -def rindex(s, *args): - """rindex(s, sub [,start [,end]]) -> int - - Like rfind but raises ValueError when the substring is not found. - - """ - return s.rindex(*args) - -# Count non-overlapping occurrences of substring -def count(s, *args): - """count(s, sub[, start[,end]]) -> int - - Return the number of occurrences of substring sub in string - s[start:end]. Optional arguments start and end are - interpreted as in slice notation. - - """ - 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 -_long = int - -# Convert string to float -def atof(s): - """atof(s) -> float - - Return the floating point number represented by the string s. - - """ - return _float(s) - - -# Convert string to integer -def atoi(s , base=10): - """atoi(s [,base]) -> int - - Return the integer represented by the string s in the given - base, which defaults to 10. The string s must consist of one - or more digits, possibly preceded by a sign. If base is 0, it - is chosen from the leading characters of s, 0 for octal, 0x or - 0X for hexadecimal. If base is 16, a preceding 0x or 0X is - accepted. - - """ - return _int(s, base) - - -# Convert string to long integer -def atol(s, base=10): - """atol(s [,base]) -> long - - Return the long integer represented by the string s in the - given base, which defaults to 10. The string s must consist - of one or more digits, possibly preceded by a sign. If base - is 0, it is chosen from the leading characters of s, 0 for - octal, 0x or 0X for hexadecimal. If base is 16, a preceding - 0x or 0X is accepted. A trailing L or l is not accepted, - unless base is 0. - - """ - return _long(s, base) - - -# Left-justify a string -def ljust(s, width, *args): - """ljust(s, width[, fillchar]) -> string - - Return a left-justified version of s, in a field of the - specified width, padded with spaces as needed. The string is - never truncated. If specified the fillchar is used instead of spaces. - - """ - return s.ljust(width, *args) - -# Right-justify a string -def rjust(s, width, *args): - """rjust(s, width[, fillchar]) -> string - - Return a right-justified version of s, in a field of the - specified width, padded with spaces as needed. The string is - never truncated. If specified the fillchar is used instead of spaces. - - """ - return s.rjust(width, *args) - -# Center a string -def center(s, width, *args): - """center(s, width[, fillchar]) -> string - - Return a center version of s, in a field of the specified - width. padded with spaces as needed. The string is never - truncated. If specified the fillchar is used instead of spaces. - - """ - return s.center(width, *args) - -# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03' -# Decadent feature: the argument may be a string or a number -# (Use of this is deprecated; it should be a string as with ljust c.s.) -def zfill(x, width): - """zfill(x, width) -> string - - Pad a numeric string x with zeros on the left, to fill a field - of the specified width. The string x is never truncated. - - """ - if not isinstance(x, basestring): - x = repr(x) - return x.zfill(width) - -# Expand tabs in a string. -# Doesn't take non-printing chars into account, but does understand \n. -def expandtabs(s, tabsize=8): - """expandtabs(s [,tabsize]) -> string - - Return a copy of the string s with all tab characters replaced - by the appropriate number of spaces, depending on the current - column, and the tabsize (default 8). - - """ - return s.expandtabs(tabsize) - -# Character translation through look-up table. -def translate(s, table, deletions=""): - """translate(s,table [,deletions]) -> string - - Return a copy of the string s, where all characters occurring - in the optional argument deletions are removed, and the - remaining characters have been mapped through the given - translation table, which must be a string of length 256. The - deletions argument is not allowed for Unicode strings. - - """ - if deletions: - return s.translate(table, deletions) - else: - # Add s[:0] so that if s is Unicode and table is an 8-bit string, - # table is converted to Unicode. This means that table *cannot* - # be a dictionary -- for that feature, use u.translate() directly. - return s.translate(table + s[:0]) - -# Capitalize a string, e.g. "aBc dEf" -> "Abc def". -def capitalize(s): - """capitalize(s) -> string - - Return a copy of the string s with only its first character - capitalized. - - """ - return s.capitalize() - -# Substring replacement (global) -def replace(s, old, new, maxsplit=-1): - """replace (str, old, new[, maxsplit]) -> string - - Return a copy of string str with all occurrences of substring - old replaced by new. If the optional argument maxsplit is - given, only the first maxsplit occurrences are replaced. - - """ - return s.replace(old, new, maxsplit) - - # Try importing optional built-in module "strop" -- if it exists, # it redefines some string operations that are 100-1000 times faster. # It also defines values for whitespace, lowercase and uppercase # that match 's definitions. try: - from strop import maketrans, lowercase, uppercase, whitespace - letters = lowercase + uppercase + from strop import maketrans except ImportError: pass # Use the original versions diff --git a/Lib/test/test_future2.py b/Lib/test/test_future2.py index 79eb73179de..3d7fc860a37 100644 --- a/Lib/test/test_future2.py +++ b/Lib/test/test_future2.py @@ -1,6 +1,6 @@ """This is a test""" -from __future__ import nested_scopes; import string +from __future__ import nested_scopes; import site def f(x): def g(y): diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py index d6dcc3c0f15..843440a9701 100644 --- a/Lib/test/test_logging.py +++ b/Lib/test/test_logging.py @@ -25,7 +25,7 @@ Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved. """ import select -import os, sys, string, struct, types, pickle, cStringIO +import os, sys, struct, types, pickle, cStringIO import socket, tempfile, threading, time import logging, logging.handlers, logging.config from test.test_support import run_with_locale @@ -455,11 +455,10 @@ datefmt= """ # config2 has a subtle configuration error that should be reported -config2 = string.replace(config1, "sys.stdout", "sys.stbout") +config2 = config1.replace("sys.stdout", "sys.stbout") # config3 has a less subtle configuration error -config3 = string.replace( - config1, "formatter=form1", "formatter=misspelled_name") +config3 = config1.replace("formatter=form1", "formatter=misspelled_name") def test4(): for i in range(4): diff --git a/Lib/test/test_scope.py b/Lib/test/test_scope.py index 5fe1bc7c026..f52ab91b56e 100644 --- a/Lib/test/test_scope.py +++ b/Lib/test/test_scope.py @@ -187,25 +187,25 @@ class ScopeTests(unittest.TestCase): check_syntax_error(self, """\ def unoptimized_clash1(strip): def f(s): - from string import * - return strip(s) # ambiguity: free or local + from sys import * + return getrefcount(s) # ambiguity: free or local return f """) check_syntax_error(self, """\ def unoptimized_clash2(): - from string import * + from sys import * def f(s): - return strip(s) # ambiguity: global or local + return getrefcount(s) # ambiguity: global or local return f """) check_syntax_error(self, """\ def unoptimized_clash2(): - from string import * + from sys import * def g(): def f(s): - return strip(s) # ambiguity: global or local + return getrefcount(s) # ambiguity: global or local return f """) @@ -219,24 +219,24 @@ def f(x): check_syntax_error(self, """\ def f(): def g(): - from string import * - return strip # global or local? + from sys import * + return getrefcount # global or local? """) # and verify a few cases that should work exec(""" def noproblem1(): - from string import * + from sys import * f = lambda x:x def noproblem2(): - from string import * + from sys import * def f(x): return x + 1 def noproblem3(): - from string import * + from sys import * def f(x): global y y = x diff --git a/Lib/test/test_string.py b/Lib/test/test_string.py index 6e9c122890d..ab75f8c50b8 100644 --- a/Lib/test/test_string.py +++ b/Lib/test/test_string.py @@ -1,67 +1,5 @@ import unittest, string -from test import test_support, string_tests -from UserList import UserList - -class StringTest( - string_tests.CommonTest, - string_tests.MixinStrStringUserStringTest - ): - - type2test = str - - def checkequal(self, result, object, methodname, *args): - realresult = getattr(string, methodname)(object, *args) - self.assertEqual( - result, - realresult - ) - - def checkraises(self, exc, object, methodname, *args): - self.assertRaises( - exc, - getattr(string, methodname), - object, - *args - ) - - def checkcall(self, object, methodname, *args): - getattr(string, methodname)(object, *args) - - def test_join(self): - # These are the same checks as in string_test.ObjectTest.test_join - # but the argument order ist different - self.checkequal('a b c d', ['a', 'b', 'c', 'd'], 'join', ' ') - self.checkequal('abcd', ('a', 'b', 'c', 'd'), 'join', '') - self.checkequal('w x y z', string_tests.Sequence(), 'join', ' ') - self.checkequal('abc', ('abc',), 'join', 'a') - self.checkequal('z', UserList(['z']), 'join', 'a') - if test_support.have_unicode: - self.checkequal(unicode('a.b.c'), ['a', 'b', 'c'], 'join', unicode('.')) - self.checkequal(unicode('a.b.c'), [unicode('a'), 'b', 'c'], 'join', '.') - self.checkequal(unicode('a.b.c'), ['a', unicode('b'), 'c'], 'join', '.') - self.checkequal(unicode('a.b.c'), ['a', 'b', unicode('c')], 'join', '.') - self.checkraises(TypeError, ['a', unicode('b'), 3], 'join', '.') - for i in [5, 25, 125]: - self.checkequal( - ((('a' * i) + '-') * i)[:-1], - ['a' * i] * i, 'join', '-') - self.checkequal( - ((('a' * i) + '-') * i)[:-1], - ('a' * i,) * i, 'join', '-') - - self.checkraises(TypeError, string_tests.BadSeq1(), 'join', ' ') - self.checkequal('a b c', string_tests.BadSeq2(), 'join', ' ') - try: - def f(): - yield 4 + "" - self.fixtype(' ').join(f()) - except TypeError as e: - if '+' not in str(e): - self.fail('join() ate exception message') - else: - self.fail('exception not raised') - - +from test import test_support class ModuleTest(unittest.TestCase): @@ -77,37 +15,14 @@ class ModuleTest(unittest.TestCase): string.punctuation string.printable - def test_atoi(self): - self.assertEqual(string.atoi(" 1 "), 1) - self.assertRaises(ValueError, string.atoi, " 1x") - self.assertRaises(ValueError, string.atoi, " x1 ") - - def test_atol(self): - self.assertEqual(string.atol(" 1 "), 1) - self.assertRaises(ValueError, string.atol, " 1x ") - self.assertRaises(ValueError, string.atol, " x1 ") - - def test_atof(self): - self.assertAlmostEqual(string.atof(" 1 "), 1.0) - self.assertRaises(ValueError, string.atof, " 1x ") - self.assertRaises(ValueError, string.atof, " x1 ") - def test_maketrans(self): transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' self.assertEqual(string.maketrans('abc', 'xyz'), transtable) self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzq') - def test_capwords(self): - self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi') - self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi') - self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi') - self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi') - self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi') - self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi') - def test_main(): - test_support.run_unittest(StringTest, ModuleTest) + test_support.run_unittest(ModuleTest) if __name__ == "__main__": test_main() diff --git a/Lib/test/test_strop.py b/Lib/test/test_strop.py index 66e7eb6d8ef..16c4cd3b613 100644 --- a/Lib/test/test_strop.py +++ b/Lib/test/test_strop.py @@ -9,126 +9,16 @@ from test import test_support class StropFunctionTestCase(unittest.TestCase): - def test_atoi(self): - self.assert_(strop.atoi(" 1 ") == 1) - self.assertRaises(ValueError, strop.atoi, " 1x") - self.assertRaises(ValueError, strop.atoi, " x1 ") - - def test_atol(self): - self.assert_(strop.atol(" 1 ") == 1) - self.assertRaises(ValueError, strop.atol, " 1x") - self.assertRaises(ValueError, strop.atol, " x1 ") - - def test_atof(self): - self.assert_(strop.atof(" 1 ") == 1.0) - self.assertRaises(ValueError, strop.atof, " 1x") - self.assertRaises(ValueError, strop.atof, " x1 ") - - def test_capitalize(self): - 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") - - def test_upper(self): - self.assert_(strop.upper("HeLLo") == "HELLO") - - def test_swapcase(self): - self.assert_(strop.swapcase("HeLLo cOmpUteRs") == "hEllO CoMPuTErS") - - def test_strip(self): - self.assert_(strop.strip(" \t\n hello \t\n ") == "hello") - - def test_lstrip(self): - self.assert_(strop.lstrip(" \t\n hello \t\n ") == "hello \t\n ") - - def test_rstrip(self): - self.assert_(strop.rstrip(" \t\n hello \t\n ") == " \t\n hello") - - def test_replace(self): - replace = strop.replace - self.assert_(replace("one!two!three!", '!', '@', 1) - == "one@two!three!") - self.assert_(replace("one!two!three!", '!', '@', 2) - == "one@two@three!") - self.assert_(replace("one!two!three!", '!', '@', 3) - == "one@two@three@") - self.assert_(replace("one!two!three!", '!', '@', 4) - == "one@two@three@") - - # CAUTION: a replace count of 0 means infinity only to strop, - # not to the string .replace() method or to the - # string.replace() function. - - self.assert_(replace("one!two!three!", '!', '@', 0) - == "one@two@three@") - self.assert_(replace("one!two!three!", '!', '@') - == "one@two@three@") - self.assert_(replace("one!two!three!", 'x', '@') - == "one!two!three!") - self.assert_(replace("one!two!three!", 'x', '@', 2) - == "one!two!three!") - - def test_split(self): - split = strop.split - self.assert_(split("this is the split function") - == ['this', 'is', 'the', 'split', 'function']) - self.assert_(split("a|b|c|d", '|') == ['a', 'b', 'c', 'd']) - self.assert_(split("a|b|c|d", '|', 2) == ['a', 'b', 'c|d']) - self.assert_(split("a b c d", None, 1) == ['a', 'b c d']) - self.assert_(split("a b c d", None, 2) == ['a', 'b', 'c d']) - self.assert_(split("a b c d", None, 3) == ['a', 'b', 'c', 'd']) - self.assert_(split("a b c d", None, 4) == ['a', 'b', 'c', 'd']) - self.assert_(split("a b c d", None, 0) == ['a', 'b', 'c', 'd']) - self.assert_(split("a b c d", None, 2) == ['a', 'b', 'c d']) - - def test_join(self): - self.assert_(strop.join(['a', 'b', 'c', 'd']) == 'a b c d') - self.assert_(strop.join(('a', 'b', 'c', 'd'), '') == 'abcd') - self.assert_(strop.join(Sequence()) == 'w x y z') - - # try a few long ones - self.assert_(strop.join(['x' * 100] * 100, ':') - == (('x' * 100) + ":") * 99 + "x" * 100) - self.assert_(strop.join(('x' * 100,) * 100, ':') - == (('x' * 100) + ":") * 99 + "x" * 100) - def test_maketrans(self): self.assert_(strop.maketrans("abc", "xyz") == transtable) self.assertRaises(ValueError, strop.maketrans, "abc", "xyzq") - def test_translate(self): - self.assert_(strop.translate("xyzabcdef", transtable, "def") - == "xyzxyz") - - def test_data_attributes(self): - strop.lowercase - strop.uppercase - strop.whitespace - transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' -# join() now works with any sequence type. -class Sequence: - def __init__(self): self.seq = 'wxyz' - def __len__(self): return len(self.seq) - def __getitem__(self, i): return self.seq[i] - - def test_main(): test_support.run_unittest(StropFunctionTestCase) - if __name__ == "__main__": test_main() diff --git a/Lib/test/test_sundry.py b/Lib/test/test_sundry.py index dcc21ac2b60..ebbe915b68a 100644 --- a/Lib/test/test_sundry.py +++ b/Lib/test/test_sundry.py @@ -55,7 +55,6 @@ import sched import smtplib import sndhdr import statvfs -import stringold import sunau import sunaudio import symbol diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py index bb3338b450e..b789fb0ba09 100644 --- a/Lib/test/test_unicode.py +++ b/Lib/test/test_unicode.py @@ -6,7 +6,7 @@ Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" -import unittest, sys, string, codecs, new +import unittest, sys, codecs, new from test import test_support, string_tests # Error handling (bad decoder return) diff --git a/Lib/urllib.py b/Lib/urllib.py index 6a2b2930cd4..60d2a413bfa 100644 --- a/Lib/urllib.py +++ b/Lib/urllib.py @@ -22,7 +22,6 @@ used to query various info about the object, if available. (mimetools.Message objects are queried with the getheader() method.) """ -import string import socket import os import time @@ -1465,6 +1464,7 @@ def reporthook(blocknum, blocksize, totalsize): # Test program def test(args=[]): + import string if not args: args = [ '/etc/passwd', diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py index aed69bbd054..19bb74772b5 100644 --- a/Lib/xml/etree/ElementTree.py +++ b/Lib/xml/etree/ElementTree.py @@ -109,7 +109,7 @@ __all__ = [ # structure, and convert it from and to XML. ## -import string, sys, re +import sys, re from . import ElementPath @@ -762,7 +762,7 @@ def _encode_entity(text, pattern=_escape): if text is None: text = "&#%d;" % ord(char) append(text) - return string.join(out, "") + return "".join(out) try: return _encode(pattern.sub(escape_entities, text), "ascii") except TypeError: @@ -772,7 +772,7 @@ def _encode_entity(text, pattern=_escape): # the following functions assume an ascii-compatible encoding # (or "utf-16") -def _escape_cdata(text, encoding=None, replace=string.replace): +def _escape_cdata(text, encoding=None): # escape character data try: if encoding: @@ -780,14 +780,14 @@ def _escape_cdata(text, encoding=None, replace=string.replace): text = _encode(text, encoding) except UnicodeError: return _encode_entity(text) - text = replace(text, "&", "&") - text = replace(text, "<", "<") - text = replace(text, ">", ">") + text = text.replace("&", "&") + text = text.replace("<", "<") + text = text.replace(">", ">") return text except (TypeError, AttributeError): _raise_serialization_error(text) -def _escape_attrib(text, encoding=None, replace=string.replace): +def _escape_attrib(text, encoding=None): # escape attribute value try: if encoding: @@ -795,11 +795,11 @@ def _escape_attrib(text, encoding=None, replace=string.replace): text = _encode(text, encoding) except UnicodeError: return _encode_entity(text) - text = replace(text, "&", "&") - text = replace(text, "'", "'") # FIXME: overkill - text = replace(text, "\"", """) - text = replace(text, "<", "<") - text = replace(text, ">", ">") + text = text.replace("&", "&") + text = text.replace("'", "'") # FIXME: overkill + text = text.replace("\"", """) + text = text.replace("<", "<") + text = text.replace(">", ">") return text except (TypeError, AttributeError): _raise_serialization_error(text) @@ -809,7 +809,7 @@ def fixtag(tag, namespaces): # tag and namespace declaration, if any if isinstance(tag, QName): tag = tag.text - namespace_uri, tag = string.split(tag[1:], "}", 1) + namespace_uri, tag = tag[1:].split("}", 1) prefix = namespaces.get(namespace_uri) if prefix is None: prefix = _namespace_map.get(namespace_uri) @@ -982,7 +982,7 @@ def tostring(element, encoding=None): file = dummy() file.write = data.append ElementTree(element).write(file, encoding) - return string.join(data, "") + return "".join(data) ## # Generic element structure builder. This builder converts a sequence @@ -1021,7 +1021,7 @@ class TreeBuilder: def _flush(self): if self._data: if self._last is not None: - text = string.join(self._data, "") + text = "".join(self._data) if self._tail: assert self._last.tail is None, "internal error (tail)" self._last.tail = text @@ -1182,7 +1182,7 @@ class XMLTreeBuilder: if prefix == ">": self._doctype = None return - text = string.strip(text) + text = text.strip() if not text: return self._doctype.append(text) diff --git a/Misc/NEWS b/Misc/NEWS index d71cd9f4bf1..4e684d4a2d5 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -169,6 +169,14 @@ Extension Modules Library ------- +- Remove functions in string module that are also string methods. + +- Remove obsolete modules: xmllib, stringold. + +- Remove support for long obsolete platforms: plat-aix3, plat-irix5. + +- Remove xmlrpclib.SlowParser. It was based on xmllib. + - Patch #1680961: atexit has been reimplemented in C. - Removed all traces of the sets module. diff --git a/Modules/stropmodule.c b/Modules/stropmodule.c index 8b00fed69a8..c5bc79b76c0 100644 --- a/Modules/stropmodule.c +++ b/Modules/stropmodule.c @@ -2,7 +2,6 @@ #define PY_SSIZE_T_CLEAN #include "Python.h" -#include PyDoc_STRVAR(strop_module__doc__, "Common string manipulations, optimized for speed.\n" @@ -10,871 +9,6 @@ PyDoc_STRVAR(strop_module__doc__, "Always use \"import string\" rather than referencing\n" "this module directly."); -/* XXX This file assumes that the is*() functions - XXX are defined for all 8-bit characters! */ - -#define WARN if (PyErr_Warn(PyExc_DeprecationWarning, \ - "strop functions are obsolete; use string methods")) \ - return NULL - -/* The lstrip(), rstrip() and strip() functions are implemented - in do_strip(), which uses an additional parameter to indicate what - type of strip should occur. */ - -#define LEFTSTRIP 0 -#define RIGHTSTRIP 1 -#define BOTHSTRIP 2 - - -static PyObject * -split_whitespace(char *s, Py_ssize_t len, Py_ssize_t maxsplit) -{ - Py_ssize_t i = 0, j; - int err; - Py_ssize_t countsplit = 0; - PyObject* item; - PyObject *list = PyList_New(0); - - if (list == NULL) - return NULL; - - while (i < len) { - while (i < len && isspace(Py_CHARMASK(s[i]))) { - i = i+1; - } - j = i; - while (i < len && !isspace(Py_CHARMASK(s[i]))) { - i = i+1; - } - if (j < i) { - item = PyString_FromStringAndSize(s+j, i-j); - if (item == NULL) - goto finally; - - err = PyList_Append(list, item); - Py_DECREF(item); - if (err < 0) - goto finally; - - countsplit++; - while (i < len && isspace(Py_CHARMASK(s[i]))) { - i = i+1; - } - if (maxsplit && (countsplit >= maxsplit) && i < len) { - item = PyString_FromStringAndSize( - s+i, len - i); - if (item == NULL) - goto finally; - - err = PyList_Append(list, item); - Py_DECREF(item); - if (err < 0) - goto finally; - - i = len; - } - } - } - return list; - finally: - Py_DECREF(list); - return NULL; -} - - -PyDoc_STRVAR(splitfields__doc__, -"split(s [,sep [,maxsplit]]) -> list of strings\n" -"splitfields(s [,sep [,maxsplit]]) -> list of strings\n" -"\n" -"Return a list of the words in the string s, using sep as the\n" -"delimiter string. If maxsplit is nonzero, splits into at most\n" -"maxsplit words. If sep is not specified, any whitespace string\n" -"is a separator. Maxsplit defaults to 0.\n" -"\n" -"(split and splitfields are synonymous)"); - -static PyObject * -strop_splitfields(PyObject *self, PyObject *args) -{ - Py_ssize_t len, n, i, j, err; - Py_ssize_t splitcount, maxsplit; - char *s, *sub; - PyObject *list, *item; - - WARN; - sub = NULL; - n = 0; - splitcount = 0; - maxsplit = 0; - if (!PyArg_ParseTuple(args, "t#|z#n:split", &s, &len, &sub, &n, &maxsplit)) - return NULL; - if (sub == NULL) - return split_whitespace(s, len, maxsplit); - if (n == 0) { - PyErr_SetString(PyExc_ValueError, "empty separator"); - return NULL; - } - - list = PyList_New(0); - if (list == NULL) - return NULL; - - i = j = 0; - while (i+n <= len) { - if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) { - item = PyString_FromStringAndSize(s+j, i-j); - if (item == NULL) - goto fail; - err = PyList_Append(list, item); - Py_DECREF(item); - if (err < 0) - goto fail; - i = j = i + n; - splitcount++; - if (maxsplit && (splitcount >= maxsplit)) - break; - } - else - i++; - } - item = PyString_FromStringAndSize(s+j, len-j); - if (item == NULL) - goto fail; - err = PyList_Append(list, item); - Py_DECREF(item); - if (err < 0) - goto fail; - - return list; - - fail: - Py_DECREF(list); - return NULL; -} - - -PyDoc_STRVAR(joinfields__doc__, -"join(list [,sep]) -> string\n" -"joinfields(list [,sep]) -> string\n" -"\n" -"Return a string composed of the words in list, with\n" -"intervening occurrences of sep. Sep defaults to a single\n" -"space.\n" -"\n" -"(join and joinfields are synonymous)"); - -static PyObject * -strop_joinfields(PyObject *self, PyObject *args) -{ - PyObject *seq; - char *sep = NULL; - Py_ssize_t seqlen, seplen = 0; - Py_ssize_t i, reslen = 0, slen = 0, sz = 100; - PyObject *res = NULL; - char* p = NULL; - ssizeargfunc getitemfunc; - - WARN; - if (!PyArg_ParseTuple(args, "O|t#:join", &seq, &sep, &seplen)) - return NULL; - if (sep == NULL) { - sep = " "; - seplen = 1; - } - - seqlen = PySequence_Size(seq); - if (seqlen < 0 && PyErr_Occurred()) - return NULL; - - if (seqlen == 1) { - /* Optimization if there's only one item */ - PyObject *item = PySequence_GetItem(seq, 0); - if (item && !PyString_Check(item)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be sequence of strings"); - Py_DECREF(item); - return NULL; - } - return item; - } - - if (!(res = PyString_FromStringAndSize((char*)NULL, sz))) - return NULL; - p = PyString_AsString(res); - - /* optimize for lists, since it's the most common case. all others - * (tuples and arbitrary sequences) just use the sequence abstract - * interface. - */ - if (PyList_Check(seq)) { - for (i = 0; i < seqlen; i++) { - PyObject *item = PyList_GET_ITEM(seq, i); - if (!PyString_Check(item)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be sequence of strings"); - Py_DECREF(res); - return NULL; - } - slen = PyString_GET_SIZE(item); - while (reslen + slen + seplen >= sz) { - if (_PyString_Resize(&res, sz * 2) < 0) - return NULL; - sz *= 2; - p = PyString_AsString(res) + reslen; - } - if (i > 0) { - memcpy(p, sep, seplen); - p += seplen; - reslen += seplen; - } - memcpy(p, PyString_AS_STRING(item), slen); - p += slen; - reslen += slen; - } - _PyString_Resize(&res, reslen); - return res; - } - - if (seq->ob_type->tp_as_sequence == NULL || - (getitemfunc = seq->ob_type->tp_as_sequence->sq_item) == NULL) - { - PyErr_SetString(PyExc_TypeError, - "first argument must be a sequence"); - return NULL; - } - /* This is now type safe */ - for (i = 0; i < seqlen; i++) { - PyObject *item = getitemfunc(seq, i); - if (!item || !PyString_Check(item)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be sequence of strings"); - Py_DECREF(res); - Py_XDECREF(item); - return NULL; - } - slen = PyString_GET_SIZE(item); - while (reslen + slen + seplen >= sz) { - if (_PyString_Resize(&res, sz * 2) < 0) { - Py_DECREF(item); - return NULL; - } - sz *= 2; - p = PyString_AsString(res) + reslen; - } - if (i > 0) { - memcpy(p, sep, seplen); - p += seplen; - reslen += seplen; - } - memcpy(p, PyString_AS_STRING(item), slen); - p += slen; - reslen += slen; - Py_DECREF(item); - } - _PyString_Resize(&res, reslen); - return res; -} - - -PyDoc_STRVAR(find__doc__, -"find(s, sub [,start [,end]]) -> in\n" -"\n" -"Return the lowest index in s where substring sub is found,\n" -"such that sub is contained within s[start,end]. Optional\n" -"arguments start and end are interpreted as in slice notation.\n" -"\n" -"Return -1 on failure."); - -static PyObject * -strop_find(PyObject *self, PyObject *args) -{ - char *s, *sub; - Py_ssize_t len, n, i = 0, last = PY_SSIZE_T_MAX; - - WARN; - if (!PyArg_ParseTuple(args, "t#t#|nn:find", &s, &len, &sub, &n, &i, &last)) - return NULL; - - if (last > len) - last = len; - if (last < 0) - last += len; - if (last < 0) - last = 0; - if (i < 0) - i += len; - if (i < 0) - i = 0; - - if (n == 0 && i <= last) - return PyInt_FromLong((long)i); - - last -= n; - for (; i <= last; ++i) - if (s[i] == sub[0] && - (n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0)) - return PyInt_FromLong((long)i); - - return PyInt_FromLong(-1L); -} - - -PyDoc_STRVAR(rfind__doc__, -"rfind(s, sub [,start [,end]]) -> int\n" -"\n" -"Return the highest index in s where substring sub is found,\n" -"such that sub is contained within s[start,end]. Optional\n" -"arguments start and end are interpreted as in slice notation.\n" -"\n" -"Return -1 on failure."); - -static PyObject * -strop_rfind(PyObject *self, PyObject *args) -{ - char *s, *sub; - Py_ssize_t len, n, j; - Py_ssize_t i = 0, last = PY_SSIZE_T_MAX; - - WARN; - if (!PyArg_ParseTuple(args, "t#t#|nn:rfind", &s, &len, &sub, &n, &i, &last)) - return NULL; - - if (last > len) - last = len; - if (last < 0) - last += len; - if (last < 0) - last = 0; - if (i < 0) - i += len; - if (i < 0) - i = 0; - - if (n == 0 && i <= last) - return PyInt_FromLong((long)last); - - for (j = last-n; j >= i; --j) - if (s[j] == sub[0] && - (n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0)) - return PyInt_FromLong((long)j); - - return PyInt_FromLong(-1L); -} - - -static PyObject * -do_strip(PyObject *args, int striptype) -{ - char *s; - Py_ssize_t len, i, j; - - - if (PyString_AsStringAndSize(args, &s, &len)) - return NULL; - - i = 0; - if (striptype != RIGHTSTRIP) { - while (i < len && isspace(Py_CHARMASK(s[i]))) { - i++; - } - } - - j = len; - if (striptype != LEFTSTRIP) { - do { - j--; - } while (j >= i && isspace(Py_CHARMASK(s[j]))); - j++; - } - - if (i == 0 && j == len) { - Py_INCREF(args); - return args; - } - else - return PyString_FromStringAndSize(s+i, j-i); -} - - -PyDoc_STRVAR(strip__doc__, -"strip(s) -> string\n" -"\n" -"Return a copy of the string s with leading and trailing\n" -"whitespace removed."); - -static PyObject * -strop_strip(PyObject *self, PyObject *args) -{ - WARN; - return do_strip(args, BOTHSTRIP); -} - - -PyDoc_STRVAR(lstrip__doc__, -"lstrip(s) -> string\n" -"\n" -"Return a copy of the string s with leading whitespace removed."); - -static PyObject * -strop_lstrip(PyObject *self, PyObject *args) -{ - WARN; - return do_strip(args, LEFTSTRIP); -} - - -PyDoc_STRVAR(rstrip__doc__, -"rstrip(s) -> string\n" -"\n" -"Return a copy of the string s with trailing whitespace removed."); - -static PyObject * -strop_rstrip(PyObject *self, PyObject *args) -{ - WARN; - return do_strip(args, RIGHTSTRIP); -} - - -PyDoc_STRVAR(lower__doc__, -"lower(s) -> string\n" -"\n" -"Return a copy of the string s converted to lowercase."); - -static PyObject * -strop_lower(PyObject *self, PyObject *args) -{ - char *s, *s_new; - Py_ssize_t i, n; - PyObject *newstr; - int changed; - - WARN; - if (PyString_AsStringAndSize(args, &s, &n)) - return NULL; - newstr = PyString_FromStringAndSize(NULL, n); - if (newstr == NULL) - return NULL; - s_new = PyString_AsString(newstr); - changed = 0; - for (i = 0; i < n; i++) { - int c = Py_CHARMASK(*s++); - if (isupper(c)) { - changed = 1; - *s_new = tolower(c); - } else - *s_new = c; - s_new++; - } - if (!changed) { - Py_DECREF(newstr); - Py_INCREF(args); - return args; - } - return newstr; -} - - -PyDoc_STRVAR(upper__doc__, -"upper(s) -> string\n" -"\n" -"Return a copy of the string s converted to uppercase."); - -static PyObject * -strop_upper(PyObject *self, PyObject *args) -{ - char *s, *s_new; - Py_ssize_t i, n; - PyObject *newstr; - int changed; - - WARN; - if (PyString_AsStringAndSize(args, &s, &n)) - return NULL; - newstr = PyString_FromStringAndSize(NULL, n); - if (newstr == NULL) - return NULL; - s_new = PyString_AsString(newstr); - changed = 0; - for (i = 0; i < n; i++) { - int c = Py_CHARMASK(*s++); - if (islower(c)) { - changed = 1; - *s_new = toupper(c); - } else - *s_new = c; - s_new++; - } - if (!changed) { - Py_DECREF(newstr); - Py_INCREF(args); - return args; - } - return newstr; -} - - -PyDoc_STRVAR(capitalize__doc__, -"capitalize(s) -> string\n" -"\n" -"Return a copy of the string s with only its first character\n" -"capitalized."); - -static PyObject * -strop_capitalize(PyObject *self, PyObject *args) -{ - char *s, *s_new; - Py_ssize_t i, n; - PyObject *newstr; - int changed; - - WARN; - if (PyString_AsStringAndSize(args, &s, &n)) - return NULL; - newstr = PyString_FromStringAndSize(NULL, n); - if (newstr == NULL) - return NULL; - s_new = PyString_AsString(newstr); - changed = 0; - if (0 < n) { - int c = Py_CHARMASK(*s++); - if (islower(c)) { - changed = 1; - *s_new = toupper(c); - } else - *s_new = c; - s_new++; - } - for (i = 1; i < n; i++) { - int c = Py_CHARMASK(*s++); - if (isupper(c)) { - changed = 1; - *s_new = tolower(c); - } else - *s_new = c; - s_new++; - } - if (!changed) { - Py_DECREF(newstr); - Py_INCREF(args); - return args; - } - return newstr; -} - - -PyDoc_STRVAR(expandtabs__doc__, -"expandtabs(string, [tabsize]) -> string\n" -"\n" -"Expand tabs in a string, i.e. replace them by one or more spaces,\n" -"depending on the current column and the given tab size (default 8).\n" -"The column number is reset to zero after each newline occurring in the\n" -"string. This doesn't understand other non-printing characters."); - -static PyObject * -strop_expandtabs(PyObject *self, PyObject *args) -{ - /* Original by Fredrik Lundh */ - char* e; - char* p; - char* q; - Py_ssize_t i, j; - PyObject* out; - char* string; - Py_ssize_t stringlen; - int tabsize = 8; - - WARN; - /* Get arguments */ - if (!PyArg_ParseTuple(args, "s#|i:expandtabs", &string, &stringlen, &tabsize)) - return NULL; - if (tabsize < 1) { - PyErr_SetString(PyExc_ValueError, - "tabsize must be at least 1"); - return NULL; - } - - /* First pass: determine size of output string */ - i = j = 0; /* j: current column; i: total of previous lines */ - e = string + stringlen; - for (p = string; p < e; p++) { - if (*p == '\t') - j += tabsize - (j%tabsize); - else { - j++; - if (*p == '\n') { - i += j; - j = 0; - } - } - } - - /* Second pass: create output string and fill it */ - out = PyString_FromStringAndSize(NULL, i+j); - if (out == NULL) - return NULL; - - i = 0; - q = PyString_AS_STRING(out); - - for (p = string; p < e; p++) { - if (*p == '\t') { - j = tabsize - (i%tabsize); - i += j; - while (j-- > 0) - *q++ = ' '; - } else { - *q++ = *p; - i++; - if (*p == '\n') - i = 0; - } - } - - return out; -} - - -PyDoc_STRVAR(count__doc__, -"count(s, sub[, start[, end]]) -> int\n" -"\n" -"Return the number of occurrences of substring sub in string\n" -"s[start:end]. Optional arguments start and end are\n" -"interpreted as in slice notation."); - -static PyObject * -strop_count(PyObject *self, PyObject *args) -{ - char *s, *sub; - Py_ssize_t len, n; - Py_ssize_t i = 0, last = PY_SSIZE_T_MAX; - Py_ssize_t m, r; - - WARN; - if (!PyArg_ParseTuple(args, "t#t#|nn:count", &s, &len, &sub, &n, &i, &last)) - return NULL; - if (last > len) - last = len; - if (last < 0) - last += len; - if (last < 0) - last = 0; - if (i < 0) - i += len; - if (i < 0) - i = 0; - m = last + 1 - n; - if (n == 0) - return PyInt_FromLong((long) (m-i)); - - r = 0; - while (i < m) { - if (!memcmp(s+i, sub, n)) { - r++; - i += n; - } else { - i++; - } - } - return PyInt_FromLong((long) r); -} - - -PyDoc_STRVAR(swapcase__doc__, -"swapcase(s) -> string\n" -"\n" -"Return a copy of the string s with upper case characters\n" -"converted to lowercase and vice versa."); - -static PyObject * -strop_swapcase(PyObject *self, PyObject *args) -{ - char *s, *s_new; - Py_ssize_t i, n; - PyObject *newstr; - int changed; - - WARN; - if (PyString_AsStringAndSize(args, &s, &n)) - return NULL; - newstr = PyString_FromStringAndSize(NULL, n); - if (newstr == NULL) - return NULL; - s_new = PyString_AsString(newstr); - changed = 0; - for (i = 0; i < n; i++) { - int c = Py_CHARMASK(*s++); - if (islower(c)) { - changed = 1; - *s_new = toupper(c); - } - else if (isupper(c)) { - changed = 1; - *s_new = tolower(c); - } - else - *s_new = c; - s_new++; - } - if (!changed) { - Py_DECREF(newstr); - Py_INCREF(args); - return args; - } - return newstr; -} - - -PyDoc_STRVAR(atoi__doc__, -"atoi(s [,base]) -> int\n" -"\n" -"Return the integer represented by the string s in the given\n" -"base, which defaults to 10. The string s must consist of one\n" -"or more digits, possibly preceded by a sign. If base is 0, it\n" -"is chosen from the leading characters of s, 0 for octal, 0x or\n" -"0X for hexadecimal. If base is 16, a preceding 0x or 0X is\n" -"accepted."); - -static PyObject * -strop_atoi(PyObject *self, PyObject *args) -{ - char *s, *end; - int base = 10; - long x; - char buffer[256]; /* For errors */ - - WARN; - if (!PyArg_ParseTuple(args, "s|i:atoi", &s, &base)) - return NULL; - - if ((base != 0 && base < 2) || base > 36) { - PyErr_SetString(PyExc_ValueError, "invalid base for atoi()"); - return NULL; - } - - while (*s && isspace(Py_CHARMASK(*s))) - s++; - errno = 0; - if (base == 0 && s[0] == '0') - x = (long) PyOS_strtoul(s, &end, base); - else - x = PyOS_strtol(s, &end, base); - if (end == s || !isalnum(Py_CHARMASK(end[-1]))) - goto bad; - while (*end && isspace(Py_CHARMASK(*end))) - end++; - if (*end != '\0') { - bad: - PyOS_snprintf(buffer, sizeof(buffer), - "invalid literal for atoi(): %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); - return NULL; - } - else if (errno != 0) { - PyOS_snprintf(buffer, sizeof(buffer), - "atoi() literal too large: %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); - return NULL; - } - return PyInt_FromLong(x); -} - - -PyDoc_STRVAR(atol__doc__, -"atol(s [,base]) -> long\n" -"\n" -"Return the long integer represented by the string s in the\n" -"given base, which defaults to 10. The string s must consist\n" -"of one or more digits, possibly preceded by a sign. If base\n" -"is 0, it is chosen from the leading characters of s, 0 for\n" -"octal, 0x or 0X for hexadecimal. If base is 16, a preceding\n" -"0x or 0X is accepted. A trailing L or l is not accepted,\n" -"unless base is 0."); - -static PyObject * -strop_atol(PyObject *self, PyObject *args) -{ - char *s, *end; - int base = 10; - PyObject *x; - char buffer[256]; /* For errors */ - - WARN; - if (!PyArg_ParseTuple(args, "s|i:atol", &s, &base)) - return NULL; - - if ((base != 0 && base < 2) || base > 36) { - PyErr_SetString(PyExc_ValueError, "invalid base for atol()"); - return NULL; - } - - while (*s && isspace(Py_CHARMASK(*s))) - s++; - if (s[0] == '\0') { - PyErr_SetString(PyExc_ValueError, "empty string for atol()"); - return NULL; - } - x = PyLong_FromString(s, &end, base); - if (x == NULL) - return NULL; - if (base == 0 && (*end == 'l' || *end == 'L')) - end++; - while (*end && isspace(Py_CHARMASK(*end))) - end++; - if (*end != '\0') { - PyOS_snprintf(buffer, sizeof(buffer), - "invalid literal for atol(): %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); - Py_DECREF(x); - return NULL; - } - return x; -} - - -PyDoc_STRVAR(atof__doc__, -"atof(s) -> float\n" -"\n" -"Return the floating point number represented by the string s."); - -static PyObject * -strop_atof(PyObject *self, PyObject *args) -{ - char *s, *end; - double x; - char buffer[256]; /* For errors */ - - WARN; - if (!PyArg_ParseTuple(args, "s:atof", &s)) - return NULL; - while (*s && isspace(Py_CHARMASK(*s))) - s++; - if (s[0] == '\0') { - PyErr_SetString(PyExc_ValueError, "empty string for atof()"); - return NULL; - } - errno = 0; - PyFPE_START_PROTECT("strop_atof", return 0) - x = PyOS_ascii_strtod(s, &end); - PyFPE_END_PROTECT(x) - while (*end && isspace(Py_CHARMASK(*end))) - end++; - if (*end != '\0') { - PyOS_snprintf(buffer, sizeof(buffer), - "invalid literal for atof(): %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); - return NULL; - } - else if (errno != 0) { - PyOS_snprintf(buffer, sizeof(buffer), - "atof() literal too large: %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); - return NULL; - } - return PyFloat_FromDouble(x); -} - - PyDoc_STRVAR(maketrans__doc__, "maketrans(frm, to) -> string\n" "\n" @@ -910,297 +44,11 @@ strop_maketrans(PyObject *self, PyObject *args) return result; } - -PyDoc_STRVAR(translate__doc__, -"translate(s,table [,deletechars]) -> string\n" -"\n" -"Return a copy of the string s, where all characters occurring\n" -"in the optional argument deletechars are removed, and the\n" -"remaining characters have been mapped through the given\n" -"translation table, which must be a string of length 256."); - -static PyObject * -strop_translate(PyObject *self, PyObject *args) -{ - register char *input, *table, *output; - Py_ssize_t i; - int c, changed = 0; - PyObject *input_obj; - char *table1, *output_start, *del_table=NULL; - Py_ssize_t inlen, tablen, dellen = 0; - PyObject *result; - int trans_table[256]; - - WARN; - if (!PyArg_ParseTuple(args, "St#|t#:translate", &input_obj, - &table1, &tablen, &del_table, &dellen)) - return NULL; - if (tablen != 256) { - PyErr_SetString(PyExc_ValueError, - "translation table must be 256 characters long"); - return NULL; - } - - table = table1; - inlen = PyString_GET_SIZE(input_obj); - result = PyString_FromStringAndSize((char *)NULL, inlen); - if (result == NULL) - return NULL; - output_start = output = PyString_AsString(result); - input = PyString_AsString(input_obj); - - if (dellen == 0) { - /* If no deletions are required, use faster code */ - for (i = inlen; --i >= 0; ) { - c = Py_CHARMASK(*input++); - if (Py_CHARMASK((*output++ = table[c])) != c) - changed = 1; - } - if (changed) - return result; - Py_DECREF(result); - Py_INCREF(input_obj); - return input_obj; - } - - for (i = 0; i < 256; i++) - trans_table[i] = Py_CHARMASK(table[i]); - - for (i = 0; i < dellen; i++) - trans_table[(int) Py_CHARMASK(del_table[i])] = -1; - - for (i = inlen; --i >= 0; ) { - c = Py_CHARMASK(*input++); - if (trans_table[c] != -1) - if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c) - continue; - changed = 1; - } - if (!changed) { - Py_DECREF(result); - Py_INCREF(input_obj); - return input_obj; - } - /* Fix the size of the resulting string */ - if (inlen > 0) - _PyString_Resize(&result, output - output_start); - return result; -} - - -/* What follows is used for implementing replace(). Perry Stoll. */ - -/* - mymemfind - - strstr replacement for arbitrary blocks of memory. - - Locates the first occurrence in the memory pointed to by MEM of the - contents of memory pointed to by PAT. Returns the index into MEM if - found, or -1 if not found. If len of PAT is greater than length of - MEM, the function returns -1. -*/ -static Py_ssize_t -mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len) -{ - register Py_ssize_t ii; - - /* pattern can not occur in the last pat_len-1 chars */ - len -= pat_len; - - for (ii = 0; ii <= len; ii++) { - if (mem[ii] == pat[0] && - (pat_len == 1 || - memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) { - return ii; - } - } - return -1; -} - -/* - mymemcnt - - Return the number of distinct times PAT is found in MEM. - meaning mem=1111 and pat==11 returns 2. - mem=11111 and pat==11 also return 2. - */ -static Py_ssize_t -mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len) -{ - register Py_ssize_t offset = 0; - Py_ssize_t nfound = 0; - - while (len >= 0) { - offset = mymemfind(mem, len, pat, pat_len); - if (offset == -1) - break; - mem += offset + pat_len; - len -= offset + pat_len; - nfound++; - } - return nfound; -} - -/* - mymemreplace - - Return a string in which all occurrences of PAT in memory STR are - replaced with SUB. - - If length of PAT is less than length of STR or there are no occurrences - of PAT in STR, then the original string is returned. Otherwise, a new - string is allocated here and returned. - - on return, out_len is: - the length of output string, or - -1 if the input string is returned, or - unchanged if an error occurs (no memory). - - return value is: - the new string allocated locally, or - NULL if an error occurred. -*/ -static char * -mymemreplace(const char *str, Py_ssize_t len, /* input string */ - const char *pat, Py_ssize_t pat_len, /* pattern string to find */ - const char *sub, Py_ssize_t sub_len, /* substitution string */ - Py_ssize_t count, /* number of replacements */ - Py_ssize_t *out_len) -{ - char *out_s; - char *new_s; - Py_ssize_t nfound, offset, new_len; - - if (len == 0 || pat_len > len) - goto return_same; - - /* find length of output string */ - nfound = mymemcnt(str, len, pat, pat_len); - if (count < 0) - count = PY_SSIZE_T_MAX; - else if (nfound > count) - nfound = count; - if (nfound == 0) - goto return_same; - - new_len = len + nfound*(sub_len - pat_len); - if (new_len == 0) { - /* Have to allocate something for the caller to free(). */ - out_s = (char *)PyMem_MALLOC(1); - if (out_s == NULL) - return NULL; - out_s[0] = '\0'; - } - else { - assert(new_len > 0); - new_s = (char *)PyMem_MALLOC(new_len); - if (new_s == NULL) - return NULL; - out_s = new_s; - - for (; count > 0 && len > 0; --count) { - /* find index of next instance of pattern */ - offset = mymemfind(str, len, pat, pat_len); - if (offset == -1) - break; - - /* copy non matching part of input string */ - memcpy(new_s, str, offset); - str += offset + pat_len; - len -= offset + pat_len; - - /* copy substitute into the output string */ - new_s += offset; - memcpy(new_s, sub, sub_len); - new_s += sub_len; - } - /* copy any remaining values into output string */ - if (len > 0) - memcpy(new_s, str, len); - } - *out_len = new_len; - return out_s; - - return_same: - *out_len = -1; - return (char *)str; /* cast away const */ -} - - -PyDoc_STRVAR(replace__doc__, -"replace (str, old, new[, maxsplit]) -> string\n" -"\n" -"Return a copy of string str with all occurrences of substring\n" -"old replaced by new. If the optional argument maxsplit is\n" -"given, only the first maxsplit occurrences are replaced."); - -static PyObject * -strop_replace(PyObject *self, PyObject *args) -{ - char *str, *pat,*sub,*new_s; - Py_ssize_t len,pat_len,sub_len,out_len; - Py_ssize_t count = -1; - PyObject *newstr; - - WARN; - if (!PyArg_ParseTuple(args, "t#t#t#|n:replace", - &str, &len, &pat, &pat_len, &sub, &sub_len, - &count)) - return NULL; - if (pat_len <= 0) { - PyErr_SetString(PyExc_ValueError, "empty pattern string"); - return NULL; - } - /* CAUTION: strop treats a replace count of 0 as infinity, unlke - * current (2.1) string.py and string methods. Preserve this for - * ... well, hard to say for what . - */ - if (count == 0) - count = -1; - new_s = mymemreplace(str,len,pat,pat_len,sub,sub_len,count,&out_len); - if (new_s == NULL) { - PyErr_NoMemory(); - return NULL; - } - if (out_len == -1) { - /* we're returning another reference to the input string */ - newstr = PyTuple_GetItem(args, 0); - Py_XINCREF(newstr); - } - else { - newstr = PyString_FromStringAndSize(new_s, out_len); - PyMem_FREE(new_s); - } - return newstr; -} - - /* List of functions defined in the module */ static PyMethodDef strop_methods[] = { - {"atof", strop_atof, METH_VARARGS, atof__doc__}, - {"atoi", strop_atoi, METH_VARARGS, atoi__doc__}, - {"atol", strop_atol, METH_VARARGS, atol__doc__}, - {"capitalize", strop_capitalize, METH_O, capitalize__doc__}, - {"count", strop_count, METH_VARARGS, count__doc__}, - {"expandtabs", strop_expandtabs, METH_VARARGS, expandtabs__doc__}, - {"find", strop_find, METH_VARARGS, find__doc__}, - {"join", strop_joinfields, METH_VARARGS, joinfields__doc__}, - {"joinfields", strop_joinfields, METH_VARARGS, joinfields__doc__}, - {"lstrip", strop_lstrip, METH_O, lstrip__doc__}, - {"lower", strop_lower, METH_O, lower__doc__}, {"maketrans", strop_maketrans, METH_VARARGS, maketrans__doc__}, - {"replace", strop_replace, METH_VARARGS, replace__doc__}, - {"rfind", strop_rfind, METH_VARARGS, rfind__doc__}, - {"rstrip", strop_rstrip, METH_O, rstrip__doc__}, - {"split", strop_splitfields, METH_VARARGS, splitfields__doc__}, - {"splitfields", strop_splitfields, METH_VARARGS, splitfields__doc__}, - {"strip", strop_strip, METH_O, strip__doc__}, - {"swapcase", strop_swapcase, METH_O, swapcase__doc__}, - {"translate", strop_translate, METH_VARARGS, translate__doc__}, - {"upper", strop_upper, METH_O, upper__doc__}, {NULL, NULL} /* sentinel */ }; @@ -1208,41 +56,9 @@ strop_methods[] = { PyMODINIT_FUNC initstrop(void) { - PyObject *m, *s; - char buf[256]; - int c, n; + PyObject *m; m = Py_InitModule4("strop", strop_methods, strop_module__doc__, (PyObject*)NULL, PYTHON_API_VERSION); if (m == NULL) return; - - /* Create 'whitespace' object */ - n = 0; - for (c = 0; c < 256; c++) { - if (isspace(c)) - buf[n++] = c; - } - s = PyString_FromStringAndSize(buf, n); - if (s) - PyModule_AddObject(m, "whitespace", s); - - /* Create 'lowercase' object */ - n = 0; - for (c = 0; c < 256; c++) { - if (islower(c)) - buf[n++] = c; - } - s = PyString_FromStringAndSize(buf, n); - if (s) - PyModule_AddObject(m, "lowercase", s); - - /* Create 'uppercase' object */ - n = 0; - for (c = 0; c < 256; c++) { - if (isupper(c)) - buf[n++] = c; - } - s = PyString_FromStringAndSize(buf, n); - if (s) - PyModule_AddObject(m, "uppercase", s); }