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

Decoding utf-8 String using python 3.6

我尝试解码成功编码的utf-8字符串,但不知道如何解码...
实际上,它的解码效果非常好,但我只想将其连接为:

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

就像我通过编码所做的一样

1
2
a = str(base64.b64encode(bytes('hasni zinda ha u are my man boy yes u are ',"utf-8")))
print('Encoding :'+a)

每当我尝试以我想要的方式进行操作时,都会出现以下错误:

1
2
3
4
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

谁能帮我解决这个问题?


继续我上面的评论。

解码Base64编码的字符串时,必须反转操作顺序:

1
2
3
4
5
6
7
>>> 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'

现在您有了编码的字符串,解码的顺序相反:

1
2
3
4
5
6
# 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()的文档,以及Base64的"输出填充"部分(需要确保将Base64编码的字符串的长度可被4整除)。

要使用两条线:

1
2
3
4
5
6
>>> 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