C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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. Signatureencode(encoding="utf-8", errors="strict") Parameters
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. # Python encode() function example # Variable declaration str = "HELLO" encode = str.encode() # Displaying result print("Old value", str) print("Encoded value", encode) Output: Old value HELLO Encoded value b 'HELLO' Python String Encode() Method Example 2We are encoding a latin character � into default encoding. # Python encode() function example # Variable declaration str = "H�LLO" encode = str.encode() # Displaying result print("Old value", str) print("Encoded value", encode) 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 # Python encode() function example # Variable declaration str = "H�LLO" encode = str.encode("ascii") # Displaying result print("Old value", str) print("Encoded value", encode) 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. # Python encode() function example # Variable declaration str = "H�LLO" encode = str.encode("ascii","ignore") # Displaying result print("Old value", str) print("Encoded value", encode) Output: Old value H�LLO Encoded value b'HLLO' Python String Encode() Method Example 5It ignores error and replace character with ? mark. # Python encode() function example # Variable declaration str = "H�LLO" encode = str.encode("ascii","replace") # Displaying result print("Old value", str) print("Encoded value", encode) Output: Old value H�LLO Encoded value b'H?LLO'
Next TopicPython Strings
|