Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7f13e6b

Browse files
committed
string.maketrans() now produces translation tables for bytes.translate() -- wrong module?
Fix all remaining instances that did bad things with the new str.translate().
1 parent 226878c commit 7f13e6b

9 files changed

Lines changed: 39 additions & 62 deletions

File tree

Doc/library/stdtypes.rst

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1549,19 +1549,18 @@ further useful methods also found on strings.
15491549
b'example'
15501550

15511551

1552-
.. method:: bytes.translate(table[, deletechars])
1552+
.. method:: bytes.translate(table[, delete])
15531553

15541554
Return a copy of the bytes object where all bytes occurring in the optional
1555-
argument *deletechars* are removed, and the remaining bytes have been mapped
1555+
argument *delete* are removed, and the remaining bytes have been mapped
15561556
through the given translation table, which must be a bytes object of length
15571557
256.
15581558

15591559
You can use the :func:`maketrans` helper function in the :mod:`string` module to
15601560
create a translation table.
15611561

15621562
.. XXX a None table doesn't seem to be supported
1563-
For string objects, set the *table* argument to
1564-
``None`` for translations that only delete characters::
1563+
Set the *table* argument to ``None`` for translations that only delete characters::
15651564
15661565
>>> 'read this short text'.translate(None, 'aeiou')
15671566
'rd ths shrt txt'

Doc/library/string.rst

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,11 @@ formatting behaviors using the same implementation as the built-in
128128
.. method:: get_field(field_name, args, kwargs, used_args)
129129

130130
Given *field_name* as returned by :meth:`parse` (see above), convert it to
131-
an object to be formatted. The default version takes strings of the form
132-
defined in :pep:`3101`, such as "0[name]" or "label.title". It records
133-
which args have been used in *used_args*. *args* and *kwargs* are as
134-
passed in to :meth:`vformat`.
131+
an object to be formatted. Returns a tuple (obj, used_key). The default
132+
version takes strings of the form defined in :pep:`3101`, such as
133+
"0[name]" or "label.title". *args* and *kwargs* are as passed in to
134+
:meth:`vformat`. The return value *used_key* has the same meaning as the
135+
*key* parameter to :meth:`get_value`.
135136

136137
.. method:: get_value(key, args, kwargs)
137138

@@ -554,15 +555,8 @@ They are not available as string methods.
554555
leading and trailing whitespace.
555556

556557

557-
.. XXX is obsolete with unicode.translate
558-
.. function:: maketrans(from, to)
558+
.. function:: maketrans(frm, to)
559559

560-
Return a translation table suitable for passing to :func:`translate`, that will
561-
map each character in *from* into the character at the same position in *to*;
562-
*from* and *to* must have the same length.
563-
564-
.. warning::
565-
566-
Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
567-
arguments; in some locales, these don't have the same length. For case
568-
conversions, always use :func:`lower` and :func:`upper`.
560+
Return a translation table suitable for passing to :meth:`bytes.translate`,
561+
that will map each character in *from* into the character at the same
562+
position in *to*; *from* and *to* must have the same length.

Lib/distutils/command/install.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -348,11 +348,10 @@ def dump_dirs(self, msg):
348348
if opt_name[-1] == "=":
349349
opt_name = opt_name[0:-1]
350350
if self.negative_opt.has_key(opt_name):
351-
opt_name = self.negative_opt[opt_name].translate(
352-
longopt_xlate)
351+
opt_name = longopt_xlate(self.negative_opt[opt_name])
353352
val = not getattr(self, opt_name)
354353
else:
355-
opt_name = opt_name.translate(longopt_xlate)
354+
opt_name = longopt_xlate(opt_name)
356355
val = getattr(self, opt_name)
357356
print(" %s: %s" % (opt_name, val))
358357

Lib/distutils/fancy_getopt.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727
# This is used to translate long options to legitimate Python identifiers
2828
# (for use as attributes of some object).
29-
longopt_xlate = string.maketrans('-', '_')
29+
longopt_xlate = lambda s: s.replace('-', '_')
3030

3131
class FancyGetopt:
3232
"""Wrapper around the standard 'getopt()' module that provides some
@@ -107,7 +107,7 @@ def get_attr_name(self, long_option):
107107
"""Translate long option name 'long_option' to the form it
108108
has as an attribute of some object: ie., translate hyphens
109109
to underscores."""
110-
return long_option.translate(longopt_xlate)
110+
return longopt_xlate(long_option)
111111

112112
def _check_alias_dict(self, aliases, what):
113113
assert isinstance(aliases, dict)
@@ -372,7 +372,7 @@ def fancy_getopt(options, negative_opt, object, args):
372372
return parser.getopt(args, object)
373373

374374

375-
WS_TRANS = string.maketrans(string.whitespace, ' ' * len(string.whitespace))
375+
WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace}
376376

377377
def wrap_text(text, width):
378378
"""wrap_text(text : string, width : int) -> [string]
@@ -432,7 +432,7 @@ def translate_longopt(opt):
432432
"""Convert a long option name to a valid Python identifier by
433433
changing "-" to "_".
434434
"""
435-
return opt.translate(longopt_xlate)
435+
return longopt_xlate(opt)
436436

437437

438438
class OptionDummy:

Lib/string.py

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,6 @@
2525
punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
2626
printable = digits + ascii_letters + punctuation + whitespace
2727

28-
# Case conversion helpers
29-
# Use str to convert Unicode literal in case of -U
30-
_idmap = str('').join(chr(c) for c in range(256))
31-
3228
# Functions which aren't available as string methods.
3329

3430
# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
@@ -44,26 +40,23 @@ def capwords(s, sep=None):
4440
return (sep or ' ').join([x.capitalize() for x in s.split(sep)])
4541

4642

47-
# Construct a translation string
48-
_idmapL = None
49-
def maketrans(fromstr, tostr):
50-
"""maketrans(frm, to) -> string
51-
52-
Return a translation table (a string of 256 bytes long)
53-
suitable for use in string.translate. The strings frm and to
54-
must be of the same length.
43+
# Construct a translation map for bytes.translate
44+
def maketrans(frm, to):
45+
"""maketrans(frm, to) -> bytes
5546
47+
Return a translation table (a bytes object of length 256)
48+
suitable for use in bytes.translate where each byte in frm is
49+
mapped to the byte at the same position in to.
50+
The strings frm and to must be of the same length.
5651
"""
57-
if len(fromstr) != len(tostr):
52+
if len(frm) != len(to):
5853
raise ValueError("maketrans arguments must have same length")
59-
global _idmapL
60-
if not _idmapL:
61-
_idmapL = list(_idmap)
62-
L = _idmapL[:]
63-
for i, c in enumerate(fromstr):
64-
L[ord(c)] = tostr[i]
65-
return ''.join(L)
66-
54+
if not (isinstance(frm, bytes) and isinstance(to, bytes)):
55+
raise TypeError("maketrans arguments must be bytes objects")
56+
L = bytes(range(256))
57+
for i, c in enumerate(frm):
58+
L[c] = to[i]
59+
return L
6760

6861

6962
####################################################################

Lib/test/test_bigmem.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
import unittest
55
import operator
6-
import string
76
import sys
87

98
# Bigmem testing houserules:
@@ -376,7 +375,7 @@ def test_title(self, size):
376375

377376
@bigmemtest(minsize=_2G, memuse=2)
378377
def test_translate(self, size):
379-
trans = string.maketrans('.aZ', '-!$')
378+
trans = {ord('.'):'-', ord('a'):'!', ord('Z'):'$'}
380379
SUBSTR = 'aZz.z.Aaz.'
381380
sublen = len(SUBSTR)
382381
repeats = size // sublen + 2

Lib/test/test_string.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,11 @@ def check_unused_args(self, used_args, args, kwargs):
103103

104104

105105
def test_maketrans(self):
106-
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'
106+
transtable = b'\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'
107107

108-
self.assertEqual(string.maketrans('abc', 'xyz'), transtable)
109-
self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzq')
108+
self.assertEqual(string.maketrans(b'abc', b'xyz'), transtable)
109+
self.assertRaises(ValueError, string.maketrans, b'abc', b'xyzq')
110+
self.assertRaises(TypeError, string.maketrans, 'abc', 'def')
110111

111112
def test_main():
112113
test_support.run_unittest(ModuleTest)

Lib/textwrap.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,6 @@ class TextWrapper:
5959
Drop leading and trailing whitespace from lines.
6060
"""
6161

62-
whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
63-
6462
unicode_whitespace_trans = {}
6563
uspace = ord(' ')
6664
for x in _whitespace:
@@ -116,10 +114,7 @@ def _munge_whitespace(self, text):
116114
if self.expand_tabs:
117115
text = text.expandtabs()
118116
if self.replace_whitespace:
119-
if isinstance(text, str8):
120-
text = text.translate(self.whitespace_trans)
121-
elif isinstance(text, str):
122-
text = text.translate(self.unicode_whitespace_trans)
117+
text = text.translate(self.unicode_whitespace_trans)
123118
return text
124119

125120

Lib/urllib.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1420,7 +1420,6 @@ def reporthook(blocknum, blocksize, totalsize):
14201420

14211421
# Test program
14221422
def test(args=[]):
1423-
import string
14241423
if not args:
14251424
args = [
14261425
'/etc/passwd',
@@ -1443,9 +1442,7 @@ def test(args=[]):
14431442
fp = open(fn, 'rb')
14441443
data = fp.read()
14451444
del fp
1446-
if '\r' in data:
1447-
table = string.maketrans("", "")
1448-
data = data.translate(table, "\r")
1445+
data = data.replace("\r", "")
14491446
print(data)
14501447
fn, h = None, None
14511448
print('-'*40)

0 commit comments

Comments
 (0)