Python String Encode() MethodPython encode() method encodes the string according to the provided encoding standard. By default Python strings are in unicode form but can be encoded to other standards also. Encoding is a process of converting text from one standard code to another. SignatureParameters
Both are optional. Default encoding is UTF-8. Error parameter has a default value strict and allows other possible values 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' etc too. Return TypeIt returns an encoded string. Let's see some examples to understand the encode() method. Python String Encode() Method Example 1A simple method which encode unicode string to utf-8 encoding standard. Output: Old value HELLO Encoded value b 'HELLO' Python String Encode() Method Example 2We are encoding a latin character Output: Old value H�LLO Encoded value b'H\xc3\x8bLLO' Python String Encode() Method Example 3We are encoding latin character into ascii, it throws an error. See the example below Output: UnicodeEncodeError: 'ascii' codec can't encode character '\xcb' in position 1: ordinal not in range(128) Python String Encode() Method Example 4If we want to ignore errors, pass ignore as the second parameter. Output: Old value H�LLO Encoded value b'HLLO' Python String Encode() Method Example 5It ignores error and replace character with ? mark. Output: Old value H�LLO Encoded value b'H?LLO' Next TopicPython Strings |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India