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?
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.
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.
The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.
The hex
codec has been chucked in 3.x. Use binascii
instead:
>>> binascii.hexlify(b'hello') b'68656c6c6f'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With