Python 无法将字节连接到 str

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21916888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:51:59  来源:igfitidea点击:

Can't concat bytes to str

python

提问by AndroidDev

This is proving to be a rough transition over to python. What is going on here?:

事实证明,这是向 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()

The output file looks like:

输出文件如下所示:

test string

test string

and then I get this error:

然后我收到这个错误:

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

采纳答案by Wooble

subprocess.check_output()returns a bytestring.

subprocess.check_output()返回一个字节串。

In Python 3, there's no implicit conversion between unicode (str) objects and bytesobjects. If you know the encoding of the output, you can .decode()it to get a string, or you can turn the \nyou want to add to byteswith "\n".encode('ascii')

在 Python 3 中,unicode ( str) 对象和bytes对象之间没有隐式转换。如果你知道输出的编码,就可以.decode()它来得到一个字符串,或者你可以把\n你想要添加到bytes"\n".encode('ascii')

回答by HISI

subprocess.check_output() returns bytes.

subprocess.check_output() 返回字节。

so you need to convert '\n' to bytes as well:

所以你还需要将 '\n' 转换为字节:

 f.write (plaintext + b'\n')

hope this helps

希望这可以帮助

回答by gcs

You can convert type of plaintextto string:

您可以将类型转换plaintext为字符串:

f.write(str(plaintext) + '\n')