How to convert 'binary string' to normal string in Python3?
Decode binary string by parsing 8-bit chunks to integers using int(binary_chunk, 2)
, then convert them to characters with chr()
. Finally, collect them together using a list comprehension:
Encoding and decoding in detail
Turning normal strings to binary
To unravel how binary strings come about, let's see how strings get encoded to binary. Encoding morphs a string into bytes (basically express shipping to Binary-ville 📦):
Remember, encode()
demands a character encoding. Common choices include 'ascii'
and 'utf-8'
, with the latter being more inclusive of diverse symbols.
From binary strings back to normal
Decoding reverts binary strings back into the realm of human-readable text. Do remember to use the same encoding used during the encoding process:
Beware the 'b' prefix
The 'b'
prefix is binary's nametag in Python, appearing when bytes are in play. Encoding appends the 'b'
prefix, while decoding politely dismisses it.
When ASCII isn't enough
But wait! What about non-ASCII or other unusual encodings? Fear not, Python has a special codecs library for those:
Advanced scenarios and curveballs
Binary padding
Sometimes binary strings have extra padding to fill up to the nearest 8-bit boundary. When converting, either remove the padding or account for it:
Special characters, Emojis, and UTF-8
For strings spiced up with special characters or emojis, 'utf-8'
is your encoding go-to, because nobody wants errors with their strings:
Error handling: a necessity
Conversion into integers or characters may hit bellies if the binary sequence is not clean. Use try-except blocks to handle these bumps:
Was this article helpful?