Search code examples
pythonhexshadigest

Hex conversion invalid escape sequence (Python)


This is my code:

from Crypto.Hash import SHA
<Receive a variable from the user, 'var'>
hashed_var = SHA.new(var).digest()
fp = open("file.txt", 'a')
for i in range(0, len(hashed_var)):
    fp.write(hex(ord(hashed_var[i]))

This essentially writes the hex representation of the hashed variable in the file. Problem is, when I view the contents of the file, there are some hex characters like \xd, \x2, etc. This throws an error when I put it in a string, I get the error message invalid \x escape. How do I fix my code so that all the hex characters come in form \xhh?


Solution

  • You can use string formatting instead of hex function:

    ...
    fp.write("\\x{0:02x}".format(ord(hashed_var[i])))