Python String encode() method
Python String encode() method
The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding
Syntax
String.encode([encoding[,errors]])
Parameter
Encoding: This parameter represents a String specifying the encoding to use and by default its value is UTF-8.
Errors: This parameter represents a String specifying the error method.
Return
This method returns an encoded version of the specified string.
Example 1
# Python program explaining # the encode() method # unicode string str = 'Hellö World!' # printing the specified string print('The given string is:', str) # default encoding to utf-8 str_utf = str.encode() # printing the encoded result print('The encoded result:', str_utf)
Output
The given string is: Hellö World ! The encoded result: b'Hell\xc3\xb6 World !'
Example 2
# Python String program explaining # the encode() method # initializing the string Str = "This is my Python String example"; # encoding the specified string Str = Str.encode('base64','strict'); # printing the encoded string print ("Encoded String: " + Str) # decoding the encoded string print "Decoded String: " + Str.decode('base64','strict')
Output
Encoded String: VGhpcyBpcyBteSBQeXRob24gU3RyaW5nIGV4YW1wbGU= Decoded String: This is my Python String example
Example 3
# Python program explaining # the encode() method # passing the unicode string string = 'Hellö Wörld!' # printing the specified string print('The given string:', string) # ignore error print('The encoded result with ignore:', string.encode("ascii", "ignore")) # replace error print('The encoded result with replace:', string.encode("ascii", "replace"))
Output
The given string: Hellö Wörld! The encoded result with ignore: b'Hell Wrld!' The encoded result with replace: b'Hell? W?rld!'