0

I have a list.txt where every line has a different hex string. So I want to choose a line and convert the specific line in ascii. So I have written this code:

import codecs
f=open('list.txt')
lines=f.readlines()
var=lines[25]
print(var)
print( codecs.decode("{var}", "hex") )

The specific var = 2d560d4b0618203249312a310d5f541f295c3f0f25235c2b20037d1600f3 when I execute this command: print( codecs.decode("2d560d4b0618203249312a310d5f541f295c3f0f25235c2b20037d1600f3", "hex") ) I get the result. But when I try to put the var variable I get this error:

Traceback (most recent call last):  File "/usr/local/lib/python3.7/encodings/hex_codec.py", line 19, in ee4'hex_decode    return (binascii.a2b_hex(input), len(input))binascii.Error: Odd-length string  
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "main.py", line 8, in <module>
print( codecs.decode("{var}", "hex") )
binascii.Error: decoding with 'hex' codec failed (Error: Odd-length string) `
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • This looks like a duplicate of https://stackoverflow.com/questions/3731278/python-binascii-a2b-hex-gives-odd-length-string There are probably white space characters in `var` causing the issue. – roasty Nov 14 '19 at 19:40
  • @roasty: In this case, the problem is `"{var}"` has nothing to do with the variable `var`. With an `f` prefix, `f"{var}"` it would, but without it, it's a literal string containing exactly five characters, `{`, `v`, `a`, `r`, and `}`. Presumably they meant to just pass `var`; there's no reason to f-string it. – ShadowRanger Mar 03 '22 at 02:51

1 Answers1

0

The new lines were being included in the string. Here is a working version that strips the white-space characters.

import codecs

f=open('list.txt')
lines=f.readlines()
var=lines[25].strip()
print(codecs.decode(var, "hex"))

Example code:https://onlinegdb.com/S1ZVk4jiH

roasty
  • 172
  • 1
  • 9