gpt4 book ai didi

python - 使用python 3.6解码utf-8字符串

转载 作者:行者123 更新时间:2023-12-04 01:38:44 24 4
gpt4 key购买 nike

我试图解码我成功编码的 utf-8 字符串,但无法弄清楚如何解码它......
实际上它解码得很好,但我只想将它与像这样连接:

b = base64.b64decode(a).decode("utf-8", "ignore")
print('Decoding:'+b)

就像我通过编码所做的那样
a = str(base64.b64encode(bytes('hasni zinda ha u are my man boy yes u are ', "utf-8")))
print('Encoding :'+a)

每当我尝试以我想要的方式进行操作时,都会出现以下错误:
File "C:/Users/…/python/first.py", line 8, in <module>
b = base64.b64decode(a).decode("utf-8", "ignore")
File "C:\Users\…\AppData\Local\Programs\Python\Python36-32\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s) binascii.Error: Incorrect padding

任何人都可以帮我解决它吗?

最佳答案

跟进我的comment above .

解码 Base64 时必须颠倒操作顺序编码字符串:

>>> s = "hasni zinda ha u are my man boy yes u are "
# Encode the Python str into bytes.
>>> b = s.encode("utf-8")
# Base64 encode the bytes.
>>> s_b64 = base64.b64encode(b)
>>> print("Encoding: " + str(s_b64))
Encoding: b'aGFzbmkgemluZGEgaGEgdSBhcmUgbXkgbWFuIGJveSB5ZXMgdSBhcmUg'

现在您有了编码的字符串,解码的工作顺序相反:
# Base64 decode the encoded string into bytes.
>>> b = base64.b64decode(s_b64)
# Decode the bytes into str.
>>> s = b.decode("utf-8")
print("Decoding: " + s)
Decoding: hasni zinda ha u are my man boy yes u are

更多详细信息,请参见 b64encode() 的文档。和 b64decode() ,以及 Output padding Base64 的部分(需要确保 Base64 编码字符串的长度可以被 4 整除)。

要使用您的双衬纸:
>>> a = base64.b64encode(bytes("hasni zinda ha u are my man boy yes u are ", "utf-8"))
>>> print("Encoding:", a)
Encoding: b'aGFzbmkgemluZGEgaGEgdSBhcmUgbXkgbWFuIGJveSB5ZXMgdSBhcmUg'
>>> b = base64.b64decode(a).decode("utf-8")
>>> print("Decoding:", b)
Decoding: hasni zinda ha u are my man boy yes u are

关于python - 使用python 3.6解码utf-8字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48352804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com