Muhammad Hassan
Muhammad Hassan

Reputation: 71

Decoding utf-8 String using python 3.6

I tried to decode the utf-8 string which I encoded successfully but can't figure out how to decode it... Actually it's decoded very well, but I just want to concatenate it with like:

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

as I did in by doing encoding

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

Whenever i try to do it in the way which i want it gives me the error about :

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

Can anyone please help me to resolve it?

Upvotes: 7

Views: 35948

Answers (1)

Jens
Jens

Reputation: 9130

Follow-up to my comment above.

You have to reverse the sequence of operation when you decode a Base64 encoded string:

>>> 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'

Now that you have the encoded string, decoding works in reverse order:

# 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 

For more details, please see the documentation for b64encode() and b64decode(), as well as the Output padding section for Base64 (required to ensure that a Base64 encoded string’s length is divisible by 4).

To use your two-liners:

>>> 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 

Upvotes: 11

Related Questions