There are several ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
On Python 2, you can also use the hex encoding like this (doesn't work on Python 3+):
>>> "c".encode("hex")
'63'
Answer from Sven Marnach on Stack OverflowThere are several ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
On Python 2, you can also use the hex encoding like this (doesn't work on Python 3+):
>>> "c".encode("hex")
'63'
This might help
import binascii
x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')
print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374
x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'
x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test
This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').
String to HEX
How do I replace a hex value in a string with something printable?
Python - Converting Hex to INT/CHAR - Stack Overflow
Converting all chars in a string to ascii hex in python - Stack Overflow
I am wanting to take a normal string, "My water bottle is blue" for example, and converting that into the HEX representation of how it would be stored in a txt file. I've tried .encode, binascii.hexlify, and a few other things. Any help would be appreciated.
If you want to get 4 separate numbers from this, then treat it as 4 separate numbers. You don't need binascii.
hex_input = 'C0A80026'
dec_output = [
int(hex_input[0:2], 16), int(hex_input[2:4], 16),
int(hex_input[4:6], 16), int(hex_input[6:8], 16),
]
print dec_output # [192, 168, 0, 38]
This can be generalised, but I'll leave it as an exercise for you.
A simple way
>>> s = 'C0A80026'
>>> map(ord, s.decode('hex'))
[192, 168, 0, 38]
>>>
if you prefer list comprehensions
>>> [ord(c) for c in s.decode('hex')]
[192, 168, 0, 38]
>>>
I suppose ''.join(r'\x{02:x}'.format(ord(c)) for c in mystring) would do the trick...
>>> 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
Based on Jon Clements's answer, try the codes on python3.7. I have the error like this:
>>> s = '1234'
>>> hexlify(s)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
hexlify(s)
TypeError: a bytes-like object is required, not 'str'
Solved by the following codes:
>>> str = '1234'.encode()
>>> hexlify(str).decode()
'31323334'