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

Skip to content

Commit 5aff775

Browse files
committed
Make string.translate(s, table) work for Unicode s. Two things are
required to work around restrictions on the arguments of u.translate(): 1) don't pass the deletions argument if it's empty; 2) convert table to Unicode if s is Unicode. This fixes SF bug #124060.
1 parent cda4f9a commit 5aff775

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

Lib/string.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -297,15 +297,22 @@ def expandtabs(s, tabsize=8):
297297

298298
# Character translation through look-up table.
299299
def translate(s, table, deletions=""):
300-
"""translate(s,table [,deletechars]) -> string
300+
"""translate(s,table [,deletions]) -> string
301301
302302
Return a copy of the string s, where all characters occurring
303-
in the optional argument deletechars are removed, and the
303+
in the optional argument deletions are removed, and the
304304
remaining characters have been mapped through the given
305-
translation table, which must be a string of length 256.
305+
translation table, which must be a string of length 256. The
306+
deletions argument is not allowed for Unicode strings.
306307
307308
"""
308-
return s.translate(table, deletions)
309+
if deletions:
310+
return s.translate(table, deletions)
311+
else:
312+
# Add s[:0] so that if s is Unicode and table is an 8-bit string,
313+
# table is converted to Unicode. This means that table *cannot*
314+
# be a dictionary -- for that feature, use u.translate() directly.
315+
return s.translate(table + s[:0])
309316

310317
# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
311318
def capitalize(s):

0 commit comments

Comments
 (0)