Python如何在codecs.decode中插入变量?

问题描述 投票:0回答:1

我有一个list.txt,其中每行都有不同的十六进制字符串。因此,我想选择一行并以ascii格式转换特定行。所以我写了这段代码:

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

特定var = 2d560d4b0618203249312a310d5f541f295c3f0f25235c2b20037d1600f3当我执行此命令时:print( codecs.decode("2d560d4b0618203249312a310d5f541f295c3f0f25235c2b20037d1600f3", "hex") )我得到了结果。但是,当我尝试放入var变量时,出现此错误:

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 stringThe 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) `
variables
1个回答
0
投票

新行已包含在字符串中。这是一个去除空白字符的工作版本。

import codecs

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

示例代码:https://onlinegdb.com/S1ZVk4jiH

© www.soinside.com 2019 - 2024. All rights reserved.