【问题标题】:Can't concat bytes to str无法将字节连接到 str
【发布时间】:2014-03-21 22:22:17
【问题描述】:

这被证明是向 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

【问题讨论】:

  • 解码明文或编码换行符。

标签: python


【解决方案1】:
f.write(plaintext)
f.write("\n".encode("utf-8"))

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • How to Answer 上,您可以找到有关格式正确答案的更多信息。你的答案可能是正确的,但很简短。
    【解决方案3】:

    subprocess.check_output() 返回字节。

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

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

    希望对你有帮助

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多