views:

239

answers:

3

I am trying to use str.encode() but I get

>>> "hello".encode(hex)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be string, not builtin_function_or_method

I have tried a bunch of variations and they seem to all work in Python 2.5.2, so what do I need to do to get them to work in Python 3.1?

+5  A: 

You've already got some good answers, but I thought you might be interested in a bit of the background too.

Firstly you're missing the quotes. It should be:

"hello".encode("hex")

Secondly this codec hasn't been ported to Python 3.1. See here. It seems that they haven't yet decided whether or not these codecs should be included in Python 3 or implemented in a different way.

If you look at the diff file attached to that bug you can see the proposed method of implementing it:

import binascii
output = binascii.b2a_hex(input)
Mark Byers
+4  A: 

The hex codec has been chucked in 3.x. Use binascii instead:

>>> binascii.hexlify(b'hello')
b'68656c6c6f'
Ignacio Vazquez-Abrams
@S.Lott: http://en.wiktionary.org/wiki/shuck#Verb sense 2
Ignacio Vazquez-Abrams
thank you, just what I was looking for
Stuart
+1  A: 

Use hexlify - http://epydoc.sourceforge.net/stdlib/binascii-module.html

Ofir
I wonder why it's called "hexlify"
Carson Myers
It was shorter than "hexlificationize" :^)
Mark Tolonen