首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python如何在codecs.decode中插入变量?

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

Stack Overflow用户
提问于 2019-11-15 03:30:23
回答 1查看 122关注 0票数 0

我有一个list.txt,其中每一行都有一个不同的十六进制string.So,我想选择一行,并转换为ascii中的特定行。所以我写了这段代码:

代码语言:javascript
复制
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变量时,我得到了这个错误:

代码语言:javascript
复制
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) `
EN

回答 1

Stack Overflow用户

发布于 2019-11-15 03:48:24

新行被包括在字符串中。下面是一个去除空格字符的工作版本。

代码语言:javascript
复制
import codecs

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58864443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档