The string method encode() used to encode the string using specified encoding value. If encoding value not specified, the default value will be UTF-8, will be considered. It returns an encoded string.
1 <string>.encode(encoding=<encoding>, errors=<errors>)
string : A source string to encode using specified values
encoding : It specifies the encoding type to encode source string, if not specified, the default will be UTF-8, Optional. ie. utf-8, ascii etc
errors : An specifies the error method, if error occurs, Optional
Possible errors values
1. | backslashreplace : it uses a backslash instead of the character that could not be encoded |
2. | ignore : it ignores the characters that can not be encoded |
3. | namereplace : It replaces the character with a text explaining the character |
4. | strict : It causes an error on failure, it is default, if not specified |
5. | replace : It replaces the character with a question mark |
6. | xmlcharrefreplace : It replaces the character with an xml character |
1 msg = "Ståle Straße"
2
3
4 s1 = msg.encode()
5 s2 = msg.encode(encoding="utf8",errors="backslashreplace")
6 s3 = msg.encode(encoding="utf8",errors="ignore")
7 s4 = msg.encode(encoding="ascii",errors="namereplace")
8 s5 = msg.encode(encoding="ascii",errors="replace")
9 s6 = msg.encode(encoding="ascii",errors="backslashreplace")
10
11
12 print(s1)
13 print(s2)
14 print(s3)
15 print(s4)
16 print(s5)
17 print(s6)
In the above example, a string variable is define with special character. A string is encoded with different encoding and errors values. An encoded string is assigned to variable that printed on console.
1 b'St\xc3\xa5le Stra\xc3\x9fe'
2 b'St\xc3\xa5le Stra\xc3\x9fe'
3 b'St\xc3\xa5le Stra\xc3\x9fe'
4 b'St\\N{LATIN SMALL LETTER A WITH RING ABOVE}le Stra\\N{LATIN SMALL LETTER SHARP S}e'
5 b'St?le Stra?e'
6 b'St\\xe5le Stra\\xdfe'
Example 2
1 str1 = "string in string !"
2
3 s1 = str1.encode(encoding="utf8",errors="backslashreplace")
4 print('Encoded string :', s1)
1 Encoded string : b'string in string !'
Related options for your search