py3k: Use string methods instead of string module

First, we go for the obvious stuff. The string module methods are gone in
3.0, so we translate them to the appropriate methods on the string class.
This commit is contained in:
Brian Crowell 2012-10-10 17:11:13 -05:00 committed by Brian Crowell
parent eaf27c93bd
commit 37f22ebfcd
28 changed files with 102 additions and 125 deletions

View File

@ -20,7 +20,6 @@
import Image
import FontFile
import string
# --------------------------------------------------------------------
# parse X Bitmap Distribution Format (BDF)
@ -50,7 +49,7 @@ def bdf_char(f):
return None
if s[:9] == "STARTCHAR":
break
id = string.strip(s[9:])
id = s[9:].strip()
# load symbol properties
props = {}
@ -58,7 +57,7 @@ def bdf_char(f):
s = f.readline()
if not s or s[:6] == "BITMAP":
break
i = string.find(s, " ")
i = s.find(" ")
props[s[:i]] = s[i+1:-1]
# load bitmap
@ -68,10 +67,10 @@ def bdf_char(f):
if not s or s[:7] == "ENDCHAR":
break
bitmap.append(s[:-1])
bitmap = string.join(bitmap, "")
bitmap = "".join(bitmap)
[x, y, l, d] = map(int, string.split(props["BBX"]))
[dx, dy] = map(int, string.split(props["DWIDTH"]))
[x, y, l, d] = map(int, props["BBX"].split())
[dx, dy] = map(int, props["DWIDTH"].split())
bbox = (dx, dy), (l, -d-y, x+l, -d), (0, 0, x, y)
@ -103,21 +102,21 @@ class BdfFontFile(FontFile.FontFile):
s = fp.readline()
if not s or s[:13] == "ENDPROPERTIES":
break
i = string.find(s, " ")
i = s.find(" ")
props[s[:i]] = s[i+1:-1]
if s[:i] in ["COMMENT", "COPYRIGHT"]:
if string.find(s, "LogicalFontDescription") < 0:
if s.find("LogicalFontDescription") < 0:
comments.append(s[i+1:-1])
font = string.split(props["FONT"], "-")
font = props["FONT"].split("-")
font[4] = bdf_slant[string.upper(font[4])]
font[11] = bdf_spacing[string.upper(font[11])]
font[4] = bdf_slant[font[4].upper()]
font[11] = bdf_spacing[font[11].upper()]
ascent = int(props["FONT_ASCENT"])
descent = int(props["FONT_DESCENT"])
fontname = string.join(font[1:], ";")
fontname = ";".join(font[1:])
# print "#", fontname
# for i in comments:

View File

@ -27,7 +27,6 @@
__version__ = "0.7"
import string
import Image, ImageFile, ImagePalette
@ -146,7 +145,7 @@ class BmpImageFile(ImageFile.ImageFile):
else:
self.mode = "P"
self.palette = ImagePalette.raw(
"BGR", string.join(palette, "")
"BGR", "".join(palette)
)
if not offset:

View File

@ -20,7 +20,7 @@
__version__ = "0.5"
import re, string
import re
import Image, ImageFile
#
@ -55,7 +55,7 @@ def Ghostscript(tile, size, fp):
"-sOutputFile=%s" % file,# output file
"- >/dev/null 2>/dev/null"]
command = string.join(command)
command = " ".join(command)
# push data through ghostscript
try:
@ -183,7 +183,7 @@ class EpsImageFile(ImageFile.ImageFile):
# Note: The DSC spec says that BoundingBox
# fields should be integers, but some drivers
# put floating point values there anyway.
box = map(int, map(float, string.split(v)))
box = map(int, map(float, v.split()))
self.size = box[2] - box[0], box[3] - box[1]
self.tile = [("eps", (0,0) + self.size, offset,
(length, box))]
@ -231,7 +231,7 @@ class EpsImageFile(ImageFile.ImageFile):
if s[:11] == "%ImageData:":
[x, y, bi, mo, z3, z4, en, id] =\
string.split(s[11:], maxsplit=7)
s[11:].split(maxsplit=7)
x = int(x); y = int(y)

View File

@ -19,7 +19,6 @@
__version__ = "0.2"
import Image, ImageFile, ImagePalette
import string
def i16(c):
@ -84,7 +83,7 @@ class FliImageFile(ImageFile.ImageFile):
self._palette(palette, 0)
palette = map(lambda (r,g,b): chr(r)+chr(g)+chr(b), palette)
self.palette = ImagePalette.raw("RGB", string.join(palette, ""))
self.palette = ImagePalette.raw("RGB", "".join(palette))
# set things up to decode first frame
self.frame = -1

View File

@ -14,7 +14,6 @@
#
from math import pi, log, sin, sqrt
import string
# --------------------------------------------------------------------
# Stuff to translate curve segments to palette values (derived from
@ -87,7 +86,7 @@ class GradientFile:
# add to palette
palette.append(r + g + b + a)
return string.join(palette, ""), "RGBA"
return "".join(palette), "RGBA"
##
# File handler for GIMP's gradient format.
@ -105,7 +104,7 @@ class GimpGradientFile(GradientFile):
for i in range(count):
s = string.split(fp.readline())
s = fp.readline().split()
w = map(float, s[:11])
x0, x1 = w[0], w[2]

View File

@ -14,7 +14,7 @@
# See the README file for information on usage and redistribution.
#
import re, string
import re
##
# File handler for GIMP's palette format.
@ -44,7 +44,7 @@ class GimpPaletteFile:
if len(s) > 100:
raise SyntaxError, "bad palette file"
v = tuple(map(int, string.split(s)[:3]))
v = tuple(map(int, s.split()[:3]))
if len(v) != 3:
raise ValueError, "bad palette entry"
@ -53,7 +53,7 @@ class GimpPaletteFile:
i = i + 1
self.palette = string.join(self.palette, "")
self.palette = "".join(self.palette)
def getpalette(self):

View File

@ -15,7 +15,7 @@
#
import Image, ImageFile
import string, struct
import struct
HEADERSIZE = 8
@ -68,7 +68,7 @@ def read_32(fobj, (start, length), size):
"Error reading channel [%r left]" % bytesleft
)
band = Image.frombuffer(
"L", size, string.join(data, ""), "raw", "L", 0, 1
"L", size, "".join(data), "raw", "L", 0, 1
)
im.im.putband(band.im, band_ix)
return {"RGB": im}

View File

@ -28,7 +28,7 @@
__version__ = "0.7"
import re, string
import re
import Image, ImageFile, ImagePalette
@ -158,8 +158,8 @@ class ImImageFile(ImageFile.ImageFile):
# Convert value as appropriate
if k in [FRAMES, SCALE, SIZE]:
v = string.replace(v, "*", ",")
v = tuple(map(number, string.split(v, ",")))
v = v.replace("*", ",")
v = tuple(map(number, v.split(",")))
if len(v) == 1:
v = v[0]
elif k == MODE and OPEN.has_key(v):

View File

@ -67,7 +67,7 @@ except ImportError, v:
import ImageMode
import ImagePalette
import os, string, sys
import os, sys
# type stuff
from types import IntType, StringType, TupleType
@ -544,7 +544,7 @@ class Image:
if s < 0:
raise RuntimeError("encoder error %d in tostring" % s)
return string.join(data, "")
return "".join(data)
##
# Returns the image converted to an X11 bitmap. This method
@ -561,9 +561,9 @@ class Image:
if self.mode != "1":
raise ValueError("not a bitmap")
data = self.tostring("xbm")
return string.join(["#define %s_width %d\n" % (name, self.size[0]),
return "".join(["#define %s_width %d\n" % (name, self.size[0]),
"#define %s_height %d\n"% (name, self.size[1]),
"static char %s_bits[] = {\n" % name, data, "};"], "")
"static char %s_bits[] = {\n" % name, data, "};"])
##
# Loads this image with pixel data from a string.
@ -1233,7 +1233,7 @@ class Image:
palette = ImagePalette.raw(data.rawmode, data.palette)
else:
if not isStringType(data):
data = string.join(map(chr, data), "")
data = "".join(map(chr, data))
palette = ImagePalette.raw(rawmode, data)
self.mode = "P"
self.palette = palette
@ -1408,7 +1408,7 @@ class Image:
preinit()
ext = string.lower(os.path.splitext(filename)[1])
ext = os.path.splitext(filename)[1].lower()
if not format:
try:
@ -1421,10 +1421,10 @@ class Image:
raise KeyError(ext) # unknown extension
try:
save_handler = SAVE[string.upper(format)]
save_handler = SAVE[format.upper()]
except KeyError:
init()
save_handler = SAVE[string.upper(format)] # unknown format
save_handler = SAVE[format.upper()] # unknown format
if isStringType(fp):
import __builtin__
@ -2093,7 +2093,7 @@ def merge(mode, bands):
# reject images having another format.
def register_open(id, factory, accept=None):
id = string.upper(id)
id = id.upper()
ID.append(id)
OPEN[id] = factory, accept
@ -2105,7 +2105,7 @@ def register_open(id, factory, accept=None):
# @param mimetype The image MIME type for this format.
def register_mime(id, mimetype):
MIME[string.upper(id)] = mimetype
MIME[id.upper()] = mimetype
##
# Registers an image save function. This function should not be
@ -2115,7 +2115,7 @@ def register_mime(id, mimetype):
# @param driver A function to save images in this format.
def register_save(id, driver):
SAVE[string.upper(id)] = driver
SAVE[id.upper()] = driver
##
# Registers an image extension. This function should not be
@ -2125,7 +2125,7 @@ def register_save(id, driver):
# @param extension An extension used for this format.
def register_extension(id, extension):
EXTENSION[string.lower(extension)] = string.upper(id)
EXTENSION[extension.lower()] = id.upper()
# --------------------------------------------------------------------

View File

@ -770,7 +770,6 @@ if __name__ == "__main__":
# create a cheap manual from the __doc__ strings for the functions above
import ImageCms
import string
print __doc__
for f in dir(pyCMS):
@ -779,7 +778,7 @@ if __name__ == "__main__":
try:
exec ("doc = ImageCms.%s.__doc__" %(f))
if string.find(doc, "pyCMS") >= 0:
if "pyCMS" in doc:
# so we don't get the __doc__ string for imported modules
print doc
except AttributeError:

View File

@ -18,15 +18,8 @@
#
import Image
import re, string
import re
try:
x = int("a", 16)
except TypeError:
# python 1.5.2 doesn't support int(x,b)
str2int = string.atoi
else:
str2int = int
##
# Convert color string to RGB tuple.
@ -43,7 +36,7 @@ def getrgb(color):
except KeyError:
try:
# fall back on case-insensitive lookup
rgb = colormap[string.lower(color)]
rgb = colormap[color.lower()]
except KeyError:
rgb = None
# found color in cache
@ -56,30 +49,30 @@ def getrgb(color):
m = re.match("#\w\w\w$", color)
if m:
return (
str2int(color[1]*2, 16),
str2int(color[2]*2, 16),
str2int(color[3]*2, 16)
int(color[1]*2, 16),
int(color[2]*2, 16),
int(color[3]*2, 16)
)
m = re.match("#\w\w\w\w\w\w$", color)
if m:
return (
str2int(color[1:3], 16),
str2int(color[3:5], 16),
str2int(color[5:7], 16)
int(color[1:3], 16),
int(color[3:5], 16),
int(color[5:7], 16)
)
m = re.match("rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
if m:
return (
str2int(m.group(1)),
str2int(m.group(2)),
str2int(m.group(3))
int(m.group(1)),
int(m.group(2)),
int(m.group(3))
)
m = re.match("rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
if m:
return (
int((str2int(m.group(1)) * 255) / 100.0 + 0.5),
int((str2int(m.group(2)) * 255) / 100.0 + 0.5),
int((str2int(m.group(3)) * 255) / 100.0 + 0.5)
int((int(m.group(1)) * 255) / 100.0 + 0.5),
int((int(m.group(2)) * 255) / 100.0 + 0.5),
int((int(m.group(3)) * 255) / 100.0 + 0.5)
)
m = re.match("hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
if m:

View File

@ -28,7 +28,7 @@
#
import Image
import traceback, string, os
import traceback, os
MAXBLOCK = 65536
@ -525,4 +525,4 @@ def _safe_read(fp, size):
break
data.append(block)
size = size - len(block)
return string.join(data, "")
return "".join(data)

View File

@ -26,7 +26,7 @@
#
import Image
import os, string, sys
import os, sys
class _imagingft_not_installed:
# module placeholder
@ -99,7 +99,7 @@ class ImageFont:
# read PILfont header
if file.readline() != "PILfont\n":
raise SyntaxError("Not a PILfont file")
d = string.split(file.readline(), ";")
d = file.readline().split(";")
self.info = [] # FIXME: should be a dictionary
while True:
s = file.readline()

View File

@ -35,7 +35,6 @@
__version__ = "0.6"
import array, struct
import string
import Image, ImageFile
def i16(c,o=0):
@ -154,7 +153,7 @@ def SOF(self, marker):
profile = []
for p in self.icclist:
profile.append(p[14:])
icc_profile = string.join(profile, "")
icc_profile = "".join(profile)
else:
icc_profile = None # wrong number of fragments
self.info["icc_profile"] = icc_profile

View File

@ -36,7 +36,7 @@
# See the README file for information on usage and redistribution.
#
import string, StringIO
import StringIO
def i16(c, o = 0):
@ -105,7 +105,7 @@ class _OleStream(StringIO.StringIO):
data.append(fp.read(sectorsize))
sect = fat[sect]
data = string.join(data, "")
data = "".join(data)
# print len(data), size

View File

@ -16,7 +16,6 @@
#
import EpsImagePlugin
import string
##
# Simple Postscript graphics interface.
@ -71,8 +70,8 @@ class PSDraw:
self.fp.write("%d %d M %d %d 0 Vr\n" % box)
def text(self, xy, text):
text = string.joinfields(string.splitfields(text, "("), "\\(")
text = string.joinfields(string.splitfields(text, ")"), "\\)")
text = "\\(".join(text.split("("))
text = "\\)".join(text.split(")"))
xy = xy + (text,)
self.fp.write("%d %d M (%s) S\n" % xy)

View File

@ -13,8 +13,6 @@
# See the README file for information on usage and redistribution.
#
import string
##
# File handler for Teragon-style palette files.
@ -37,7 +35,7 @@ class PaletteFile:
if len(s) > 100:
raise SyntaxError, "bad palette file"
v = map(int, string.split(s))
v = map(int, s.split())
try:
[i, r, g, b] = v
except ValueError:
@ -47,7 +45,7 @@ class PaletteFile:
if 0 <= i <= 255:
self.palette[i] = chr(r) + chr(g) + chr(b)
self.palette = string.join(self.palette, "")
self.palette = "".join(self.palette)
def getpalette(self):

View File

@ -19,8 +19,6 @@
import Image
import FontFile
import string
# --------------------------------------------------------------------
# declarations
@ -55,7 +53,7 @@ def b32(c):
return ord(c[3]) + (ord(c[2])<<8) + (ord(c[1])<<16) + (ord(c[0])<<24)
def sz(s, o):
return s[o:string.index(s, "\0", o)]
return s[o:s.index("\0", o)]
##
# Font file plugin for the X11 PCF format.

View File

@ -33,7 +33,7 @@
__version__ = "0.9"
import re, string
import re
import Image, ImageFile, ImagePalette, zlib
@ -189,7 +189,7 @@ class PngStream(ChunkStream):
# Null separator 1 byte (null character)
# Compression method 1 byte (0)
# Compressed profile n bytes (zlib with deflate compression)
i = string.find(s, chr(0))
i = s.find(chr(0))
if Image.DEBUG:
print "iCCP profile name", s[:i]
print "Compression method", ord(s[i])
@ -243,7 +243,7 @@ class PngStream(ChunkStream):
# transparency
s = ImageFile._safe_read(self.fp, len)
if self.im_mode == "P":
i = string.find(s, chr(0))
i = s.find(chr(0))
if i >= 0:
self.im_info["transparency"] = i
elif self.im_mode == "L":
@ -277,7 +277,7 @@ class PngStream(ChunkStream):
# text
s = ImageFile._safe_read(self.fp, len)
try:
k, v = string.split(s, "\0", 1)
k, v = s.split("\0", 1)
except ValueError:
k = s; v = "" # fallback for broken tEXt tags
if k:
@ -288,7 +288,7 @@ class PngStream(ChunkStream):
# compressed text
s = ImageFile._safe_read(self.fp, len)
k, v = string.split(s, "\0", 1)
k, v = s.split("\0", 1)
comp_method = ord(v[0])
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in zTXt chunk" % comp_method)
@ -443,7 +443,7 @@ _OUTMODES = {
def putchunk(fp, cid, *data):
"Write a PNG chunk (including CRC field)"
data = string.join(data, "")
data = "".join(data)
fp.write(o32(len(data)) + cid)
fp.write(data)
@ -593,7 +593,7 @@ def getchunks(im, **params):
self.data.append(chunk)
def append(fp, cid, *data):
data = string.join(data, "")
data = "".join(data)
hi, lo = Image.core.crc32(data, Image.core.crc32(cid))
crc = o16(hi) + o16(lo)
fp.append((cid, data, crc))

View File

@ -15,7 +15,6 @@
#
import ContainerIO
import string
##
# A file object that provides read access to a given member of a TAR
@ -40,13 +39,13 @@ class TarIO(ContainerIO.ContainerIO):
raise IOError, "unexpected end of tar file"
name = s[:100]
i = string.find(name, chr(0))
i = name.find(chr(0))
if i == 0:
raise IOError, "cannot find subfile"
if i > 0:
name = name[:i]
size = string.atoi(s[124:136], 8)
size = int(s[124:136], 8)
if file == name:
break

View File

@ -44,7 +44,7 @@ __version__ = "1.3.5"
import Image, ImageFile
import ImagePalette
import array, string, sys
import array, sys
II = "II" # little-endian (intel-style)
MM = "MM" # big-endian (motorola-style)
@ -422,14 +422,14 @@ class ImageFileDirectory:
if typ == 1:
# byte data
data = value = string.join(map(chr, value), "")
data = value = "".join(map(chr, value))
elif typ == 7:
# untyped data
data = value = string.join(value, "")
data = value = "".join(value)
elif type(value[0]) is type(""):
# string data
typ = 2
data = value = string.join(value, "\0") + "\0"
data = value = "\0".join(value) + "\0"
else:
# integer data
if tag == STRIPOFFSETS:
@ -444,9 +444,9 @@ class ImageFileDirectory:
if v >= 65536:
typ = 4
if typ == 3:
data = string.join(map(o16, value), "")
data = "".join(map(o16, value))
else:
data = string.join(map(o32, value), "")
data = "".join(map(o32, value))
if Image.DEBUG:
import TiffTags
@ -705,7 +705,7 @@ class TiffImageFile(ImageFile.ImageFile):
if self.mode == "P":
palette = map(lambda a: chr(a / 256), self.tag[COLORMAP])
self.palette = ImagePalette.raw("RGB;L", string.join(palette, ""))
self.palette = ImagePalette.raw("RGB;L", "".join(palette))
#
# --------------------------------------------------------------------
# Write TIFF files

View File

@ -19,7 +19,6 @@
__version__ = "0.1"
import string
import Image, ImageFile, ImagePalette
# standard color palette for thumbnails (RGB332)
@ -56,7 +55,7 @@ class XVThumbImageFile(ImageFile.ImageFile):
break
# parse header line (already read)
s = string.split(s.strip())
s = s.strip().split()
self.mode = "P"
self.size = int(s[0]), int(s[1])

View File

@ -21,7 +21,7 @@
__version__ = "0.6"
import re, string
import re
import Image, ImageFile
# XBM header
@ -36,7 +36,7 @@ xbm_head = re.compile(
)
def _accept(prefix):
return string.lstrip(prefix)[:7] == "#define"
return prefix.lstrip()[:7] == "#define"
##
# Image plugin for X11 bitmaps.

View File

@ -18,7 +18,7 @@
__version__ = "0.2"
import re, string
import re
import Image, ImageFile, ImagePalette
# XPM header
@ -72,7 +72,7 @@ class XpmImageFile(ImageFile.ImageFile):
s = s[:-1]
c = ord(s[1])
s = string.split(s[2:-2])
s = s[2:-2].split()
for i in range(0, len(s), 2):
@ -84,7 +84,7 @@ class XpmImageFile(ImageFile.ImageFile):
self.info["transparency"] = c
elif rgb[0] == "#":
# FIXME: handle colour names (see ImagePalette.py)
rgb = string.atoi(rgb[1:], 16)
rgb = int(rgb[1:], 16)
palette[c] = chr((rgb >> 16) & 255) +\
chr((rgb >> 8) & 255) +\
chr(rgb & 255)
@ -99,7 +99,7 @@ class XpmImageFile(ImageFile.ImageFile):
raise ValueError, "cannot read this XPM file"
self.mode = "P"
self.palette = ImagePalette.raw("RGB", string.join(palette, ""))
self.palette = ImagePalette.raw("RGB", "".join(palette))
self.tile = [("raw", (0, 0)+self.size, self.fp.tell(), ("P", 0, 1))]
@ -113,11 +113,11 @@ class XpmImageFile(ImageFile.ImageFile):
s = [None] * ysize
for i in range(ysize):
s[i] = string.ljust(self.fp.readline()[1:xsize+1], xsize)
s[i] = self.fp.readline()[1:xsize+1].ljust(xsize)
self.fp = None
return string.join(s, "")
return "".join(s)
#
# Registry

View File

@ -46,7 +46,6 @@ class Option:
"""
def __init__(self, args, scanDev):
import string
self.scanDev = scanDev # needed to get current value of this option
self.index, self.name = args[0], args[1]
self.title, self.desc = args[2], args[3]
@ -57,7 +56,7 @@ class Option:
if x=='-': return '_'
else: return x
if type(self.name)!=type(''): self.py_name=str(self.name)
else: self.py_name=string.join(map(f, self.name), '')
else: self.py_name=''.join(map(f, self.name))
def is_active(self):
return _sane.OPTION_IS_ACTIVE(self.cap)

View File

@ -6,7 +6,7 @@
#
from PIL import Image
import os, string, sys
import os, sys
class Interval:
@ -18,18 +18,18 @@ class Interval:
self.hilo = []
for s in string.split(interval, ","):
if not string.strip(s):
for s in interval.split(","):
if not s.strip():
continue
try:
v = string.atoi(s)
v = int(s)
if v < 0:
lo, hi = 0, -v
else:
lo = hi = v
except ValueError:
i = string.find(s, "-")
lo, hi = string.atoi(s[:i]), string.atoi(s[i+1:])
i = s.find("-")
lo, hi = int(s[:i]), int(s[i+1:])
self.hilo.append((hi, lo))
@ -69,7 +69,7 @@ if not sys.argv[2:]:
infile = sys.argv[1]
outfile = sys.argv[2]
frames = Interval(string.join(sys.argv[3:], ","))
frames = Interval(",".join(sys.argv[3:]))
try:
# check if outfile contains a placeholder

View File

@ -40,7 +40,6 @@
#
from PIL import Image, ImageChops
import string
from PIL.GifImagePlugin import getheader, getdata

View File

@ -49,7 +49,6 @@ of its upper-left-hand corner and displays the cropped portion.
#
from PIL import Image
import string
class PILDriver:
@ -206,7 +205,7 @@ class PILDriver:
Process the top image with the given filter.
"""
import ImageFilter
filter = eval("ImageFilter." + string.upper(self.do_pop()))
filter = eval("ImageFilter." + self.do_pop().upper())
image = self.do_pop()
self.push(image.filter(filter))
@ -314,7 +313,7 @@ class PILDriver:
Transpose the top image.
"""
transpose = string.upper(self.do_pop())
transpose = self.do_pop().upper()
image = self.do_pop()
self.push(image.transpose(transpose))
@ -515,7 +514,7 @@ if __name__ == '__main__':
except EOFError:
print "\nPILDriver says goodbye."
break
driver.execute(string.split(line))
driver.execute(line.split())
print driver.stack
# The following sets edit modes for GNU EMACS