Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come string.maketrans does not work in Python 3.1?

Tags:

I'm a Python newbie.

How come this doesn't work in Python 3.1?

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab);

When I executed the above code, I get the following instead:

Traceback (most recent call last):
  File "<pyshell#119>", line 1, in <module>
    transtab = maketrans(intab, outtab)
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/string.py", line 60, in maketrans
    raise TypeError("maketrans arguments must be bytes objects")
TypeError: maketrans arguments must be bytes objects

What does "must be bytes objects" mean? Could anyone please help post a working code for Python 3.1 if it's possible?

like image 615
sivabudh Avatar asked Jun 13 '10 04:06

sivabudh


2 Answers

You don't need to use bytes.maketrans() when str would be simpler and eliminate the need for the 'b' prefix:

print("Swap vowels for numbers.".translate(str.maketrans('aeiou', '12345')))
like image 188
theNewt Avatar answered Oct 11 '22 06:10

theNewt


Stop trying to learn Python 3 by reading Python 2 documentation.

intab = 'aeiou'
outtab = '12345'

s = 'this is string example....wow!!!'

print(s.translate({ord(x): y for (x, y) in zip(intab, outtab)}))
like image 42
Ignacio Vazquez-Abrams Avatar answered Oct 11 '22 05:10

Ignacio Vazquez-Abrams