提问人:AndroidDev 提问时间:2/21/2014 更新时间:6/25/2020 访问量:183825
无法将字节转换为 str
Can't concat bytes to str
问:
事实证明,这是向 python 的粗略过渡。这是怎么回事?
f = open( 'myfile', 'a+' )
f.write('test string' + '\n')
key = "pass:hello"
plaintext = subprocess.check_output(['openssl', 'aes-128-cbc', '-d', '-in', test, '-base64', '-pass', key])
print (plaintext)
f.write (plaintext + '\n')
f.close()
输出文件如下所示:
test string
然后我收到这个错误:
b'decryption successful\n'
Traceback (most recent call last):
File ".../Project.py", line 36, in <module>
f.write (plaintext + '\n')
TypeError: can't concat bytes to str
答:
48赞
Wooble
2/21/2014
#1
subprocess.check_output()
返回 bytestring。
在 Python 3 中,unicode () 对象和对象之间没有隐式转换。如果你知道输出的编码,你可以用它来获取一个字符串,或者你可以将你想添加的str
bytes
.decode()
\n
bytes
"\n".encode('ascii')
15赞
HISI
10/25/2017
#2
subprocess.check_output() 返回字节。
因此,您还需要将 '\n' 转换为字节:
f.write (plaintext + b'\n')
希望这会有所帮助
2赞
gcs
7/17/2019
#3
您可以将 type of 转换为字符串:plaintext
f.write(str(plaintext) + '\n')
评论
0赞
Stef Geysels
7/17/2019
在“如何回答”中,您可以找到有关格式正确的答案的更多信息。你的答案可能是正确的,但它很简短。
1赞
Ravi Prakash
6/25/2020
#4
f.write(plaintext)
f.write("\n".encode("utf-8"))
评论