Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.1.1 string to hex

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?

like image 769
Stuart Avatar asked Feb 26 '10 08:02

Stuart


People also ask

Can you convert string to hex in Python?

To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.

How do you make a hexadecimal in Python?

To generate a random hex string in Python, use one of the two functions from the secrets module – token_hex(n) or choice() – if security is a concern. Otherwise, you can use the choice() function from the random module. Another elegant solution is to use Python's string formatting methods.

What does .encode do in Python?

The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.


2 Answers

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

>>> binascii.hexlify(b'hello') b'68656c6c6f' 
like image 185
Ignacio Vazquez-Abrams Avatar answered Oct 04 '22 07:10

Ignacio Vazquez-Abrams


In Python 3.5+, encode the string to bytes and use the hex() method, returning a string.

s = "hello".encode("utf-8").hex() s # '68656c6c6f' 

Optionally convert the string back to bytes:

b = bytes(s, "utf-8") b # b'68656c6c6f' 
like image 41
pylang Avatar answered Oct 04 '22 06:10

pylang