Please look at the binascii module to see if it has a function that does what you want. It's a C extension so it will run much faster than writing your own function in Python.