You can encode()the string:

string = "{'id':'other_aud1_aud2','kW':15}"
h = hexlify(string.encode())
print(h.decode())
# 7b276964273a276f746865725f617564315f61756432272c276b57273a31357d

s = unhexlify(hex).decode()
print(s) 
# {'id':'other_aud1_aud2','kW':15}
Answer from Mark on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › converting string to ascii hex python 3
r/learnpython on Reddit: Converting string to ASCII HEX Python 3
November 22, 2020 -

Hi all,

I've been struggling with this for an hour or so, I'm trying to take a string such as

'Hell' to '\x48\x65\x6c\x6c'

For what I'm doing, I require the \x before the ascii hex

This is a dated solution from StackOverflow, that doesn't work on Python3

>>> mystring = "Hello World"
>>> print ''.join(r'\x{02:x}'.format(ord(c)) for c in mystring)
\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64                

My new solution goes like this:

mystring = b'hello world'

#convert to hex
mystring = hexlify(mystring)
mystring = mystring.decode('ascii')
# hex, like this 68656c6c6f20776f726c64

#add in the \x in the right spots
mystring = '\\x'.join(mystring[i:i + 2] for i in range(-2, len(mystring), 2)) 
#looks like this at this point \x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64

#I need it back into the "b" format, so I encode it 
mystring=mystring.encode(ascii)
# This breaks everything, now it becomes:
# b'\\x68\\x65\\x6c\\x6c\\x6f\\x20\\x77\\x6f\\x72\\x6c\\x64'
# I specifically can't use the double backslashes.

Any ideas how to fix this or am I going about this all wrong? Thanks

Need help converting ascii to hex. May 26, 2017
r/learnpython
9y ago
[01/14/13] Challenge #117 [Easy] Hexdump to ASCII Jan 14, 2013
r/dailyprogrammer
13y ago
How to convert a file to HEX then back with Python? Aug 21, 2020
r/learnpython
6y ago
Script for Hex to ASCII Text Converter Apr 6, 2020
r/learnprogramming
6y ago
More results from reddit.com
Top answer
1 of 2
6

You can encode()the string:

string = "{'id':'other_aud1_aud2','kW':15}"
h = hexlify(string.encode())
print(h.decode())
# 7b276964273a276f746865725f617564315f61756432272c276b57273a31357d

s = unhexlify(hex).decode()
print(s) 
# {'id':'other_aud1_aud2','kW':15}
2 of 2
1

The tricky bit here is that a Python 3 string is a sequence of Unicode characters, which is not the same as a sequence of ASCII characters.

  • In Python2, the str type and the bytes type are synonyms, and there is a separate type, unicode, that represents a sequence of Unicode characters. This makes it something of a mystery, if you have a string: is it a sequence of bytes, or is it a sequence of characters in some character-set?

  • In Python3, str now means unicode and we use bytes for what used to be str. Given a string—a sequence of Unicode characters—we use encode to convert it to some byte-sequence that can represent it, if there is such a sequence:

    >>> 'hello'.encode('ascii')
    b'hello'
    >>> 'sch\N{latin small letter o with diaeresis}n'
    'schön'
    >>> 'sch\N{latin small letter o with diaeresis}n'.encode('utf-8')
    b'sch\xc3\xb6n'
    

    but:

    >>> 'sch\N{latin small letter o with diaeresis}n'.encode('ascii')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 3: ordinal not in range(128)
    

Once you have the bytes object, you already know what to do. In Python2, if you have a str, you have a bytes object; in Python3, use .encode with your chosen encoding.

Discussions

How to convert character to hexadecimal and back?
I tried to code to convert string to hexdecimal and back for controle as follows: input = 'Україна' table = [] for item in input: table.append(item.encode('utf-8').hex()) output = '' for item in table: output += chr(int(item, 16)) print(output) To my surprise the output is total different ... More on discuss.python.org
🌐 discuss.python.org
6
0
March 22, 2023
String to HEX
I've tried .encode, binascii.hexlify, and a few other things. Ok, well, encode was the correct one, so do that. More on reddit.com
🌐 r/learnpython
7
5
September 2, 2024
python - Convert from ASCII string encoded in Hex to plain ASCII? - Stack Overflow
How can I convert from hex to plain ASCII in Python? Note that, for example, I want to convert "0x7061756c" to "paul". More on stackoverflow.com
🌐 stackoverflow.com
data conversion - How can I change ascii string to hex and vice versa in python 3.7? - Stack Overflow
I look some solution in this site but those not works in python 3.7. So, I asked a new question. Hex string of "the" is "746865" I want to a solution to convert "the" to "746865" and "746865" to ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › convert-hexadecimal-value-string-ascii-value-string
Convert Hexadecimal value String to ASCII value String - GeeksforGeeks
July 11, 2025 - Extract first two characters from the hexadecimal string taken as input. Convert it into base 16 integer. Cast this integer to character which is ASCII equivalent of 2 char hex.
🌐
Python Forum
python-forum.io › thread-1715.html
how to convert a string to hex
January 22, 2017 - what is the best way to convert a string to hexadecimal? the purpose is to get the character codes to see what is being read in from a file. i already have command line tools that display the file in
🌐
Python.org
discuss.python.org › python help
How to convert character to hexadecimal and back? - Python Help - Discussions on Python.org
March 22, 2023 - I tried to code to convert string ... follows: input = 'Україна' table = [] for item in input: table.append(item.encode('utf-8').hex()) output = '' for item in table: output += chr(int(item, 16)) print(output) To my surprise ...
Find elsewhere
🌐
Skillsugar
skillsugar.com › how-to-convert-a-string-from-hex-to-ascii-in-python
How to Convert a String from Hex to ASCII in Python - SkillSugar
April 27, 2021 - In this tutorial, we will learn how to convert a hexadecimal string from its base-16 encoding into its ASCII representation. To do this we will need to perform two operations. The first is to create a bytes object from the hex string using the Python bytes.fromhex() function and convert that ...
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "python how-to's" › "how to convert hex to ascii in python"
How to Convert Hex to ASCII in Python | Delft Stack
February 2, 2024 - Suppose we have a string written in hexadecimal form, 68656c6c6f, and we want to convert it into an ASCII string, which will be hello (in ASCII code h = 68, e = 65, l = 6c and o = 6f). The string.decode(encoding, error) method in Python 2 takes an encoded string as input and decodes it using ...
🌐
CodeSpeedy
codespeedy.com › home › convert hex to ascii in python
Convert Hex to ASCII in Python - CodeSpeedy
April 18, 2022 - Explanation: Initially, we declare a variable and initialize it to a hexadecimal value. In the second step we slice the given value, you can refer to How to slice a string in Python – Multiple way. For the rest of the conversion, methods bytes.fromhex() and decode() are used. In the output, Ascii value is displayed.
🌐
Python Guides
pythonguides.com › convert-string-to-hexadecimal-in-python
How to Convert String to Hex in Python?
April 3, 2025 - The most simple approach to convert a string to hex in Python is to use the string’s encode() method to get a bytes representation, then apply the hex() method to convert those bytes to a hexadecimal string.
🌐
GeeksforGeeks
geeksforgeeks.org › python-hex-function
hex() function in Python - GeeksforGeeks
May 9, 2025 - Example: ... Explanation: hex() function takes that number and converts it into its hexadecimal representation, which is 0xff. The result is stored in res. ... Parameter: x is an integer number (of type int).
🌐
Acme
acme.to › 2021 › 11 › 20 › python-convert-hex-to-ascii
Python convert hex to ascii – acme
But my strings can and will include letters like “áðéíóþæ”. The sting comes from snmp and in this example I will be using the word “Ísland” for this demo hex “cd 73 6c 61 6e 64” Here is one of the most promising code snipped · import binascii def hex_to_ascii(hex_str): hex_str = hex_str.replace(' ', '').replace('0x', '').replace('\t', '').replace('\n', '') ascii_str = binascii.unhexlify(hex_str) return ascii_str hex_input = 'cd 73 6c 61 6e 64' ascii_output = hex_to_ascii(hex_input) print(format(ascii_output))
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › convert-a-string-to-hexadecimal-ascii-values
Convert a string to hexadecimal ASCII values - GeeksforGeeks
The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system. The hexadecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all numbers.
Published: July 11, 2025
🌐
ActiveState
code.activestate.com › recipes › 496969-convert-string-to-hex
Convert string to hex « Python recipes « ActiveState Code
toHex = lambda x:"".join([hex(ord(c))[2:].zfill(2) for c in x]) The builtin string-method "join" joins every element of the list to the string by re-using the string.