Remember to import base64 and that the b64encode function takes bytes as an argument.
import base64
b = base64.b64encode(bytes('your_string', 'utf-8')) # bytes
base64_str = b.decode('utf-8') # convert bytes to string
Explanation:
The bytes function creates a bytes object from the string "your_string" using UTF-8 encoding. In Python, bytes represents a sequence of bits and UTF-8 specifies the character encoding to use.
The base64.b64encode function encodes bytes object into Base64 format. It takes a bytes-like object as input and returns a Base64 encoded bytes object.
The b.decode function decodes the bytes object (here b) using UTF-8 encoding and returns the resulting string. It converts the bytes back to their original string representation.
How to encode text to base64 in python - Stack Overflow
Base64 encode of image too long
Converting string to mp4 video file
Is Base64 encoded UUID still unique?
base64 encoding does not shorten the data, it makes it longer. It converts 3 bytes of data into 4 readable characters. It is not lossy, you can convert it back to the original bytes with a base64 decode.
If the original bytes were unique, the base64 string should be unique as well.
Edit -- maybe I'm misunderstanding the question? If you are truncating the data, you won't guarantee uniqueness anymore. Depending on the level of truncations, collisions might be rare, but they'll still be possible.
More on reddit.comRemember to import base64 and that the b64encode function takes bytes as an argument.
import base64
b = base64.b64encode(bytes('your_string', 'utf-8')) # bytes
base64_str = b.decode('utf-8') # convert bytes to string
Explanation:
The bytes function creates a bytes object from the string "your_string" using UTF-8 encoding. In Python, bytes represents a sequence of bits and UTF-8 specifies the character encoding to use.
The base64.b64encode function encodes bytes object into Base64 format. It takes a bytes-like object as input and returns a Base64 encoded bytes object.
The b.decode function decodes the bytes object (here b) using UTF-8 encoding and returns the resulting string. It converts the bytes back to their original string representation.
For py3, base64 encode and decode string :
import base64
def b64e(s):
return base64.b64encode(s.encode()).decode()
def b64d(s):
return base64.b64decode(s).decode()