What is base64.urlsafe_b64encode(s) in Python?
The base64.urlsafe_b64encode() method encodes a byte-like object into binary form using the URL and file system safe alphabets. This encoding replaces "+" with "-" and "_" with "/" of the Base64 characters.
Syntax
We can import urlsafe_b64encode from base64 using the following code:
from base64 import urlsafe_b64encode
The declaration of the base64.urlsafe_b64encode() method is as follows:
base64.urlsafe_b64encode(b_string)
The method returns the encoded bytes for the byte-string provided as an argument.
Code
The code below demonstrates the use of base64.urlsafe_b64encode().
from base64 import urlsafe_b64encodeb_str = b'Python is awesome!'print('Data type of \'b_str\': ', type(b_str))enc_str = urlsafe_b64encode(b_str)print('Data type of encoded \'enc_str\': ', type(enc_str))print('Encoded string: ', enc_str)
Explanation
In line 3, a byte string is initialized and stored in the variable, b_str. The next line prints the type of b_str. Then, in line 6, the string is encoded, and line 7 prints the type of the encoded string. Finally, in line 9, the encoded string is printed.
Free Resources