views:

268

answers:

4

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?

+3  A: 

Strings are not bytes.

This is a simple definition in Python 3.

Strings are Unicode (which are not bytes) Unicode strings use "..." or '...'

Bytes are bytes (which are not strings) Byte strings use b"..." or b'...'.

Use b"aeiou" to create a byte sequence composed of the ASCII codes for certain letters.

S.Lott
Thanks for the help. The only thing I was missing was just the "b" prefix.
ShaChris23
+1  A: 

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

intab = 'aeiou'
outtab = '12345'

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

print(s.translate(dict((ord(x), y) for (x, y) in zip(intab, outtab))))
Ignacio Vazquez-Abrams
Pardon me, but as a newbie, I have no clue which is P2 doc, and which is P3. Thanks for the code though.
ShaChris23
A: 

If you absolutely insist on working with 8-bit bytes:

>>> intab = b"aeiou"
>>> outtab = b"12345"
>>> trantab = bytes.maketrans(intab, outtab)
>>> strg = b"this is string example....wow!!!";
>>> print(strg.translate(trantab));
b'th3s 3s str3ng 2x1mpl2....w4w!!!'
>>>
John Machin
A: 

Here's my final Python (3.1) code posted here just for reference:

"this is string example....wow!!!".translate(bytes.maketrans(b"aeiou",b"12345"))

Short and sweet, love it.

ShaChris23