The string method decode() used to decode the string using specified decoded value. If decoding value not specified, the default value will be UTF-8, will be considered. It returns the original string from the encoded string.
1 <string>.decode(encoding = <encoding>, errors = <errors>)
string : A encoded source string to decode using specified values.
encoding : It specifies the encoding on the basis of which decoding has to be performed. ie. utf-8, ascii etc
errors : An specifies the error method, if error occurs, Optional
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 import pandas as pd
2
3 msg = 'Ståle Straße'
4
5
6 s1 = msg.encode()
7 s2 = msg.encode(encoding = 'utf8', errors = 'backslashreplace')
8 s3 = msg.encode(encoding = 'utf8', errors = 'ignore')
9
10
11 print(s1.decode())
12 print(s2.decode(encoding = 'utf8', errors = 'backslashreplace'))
13 print(s3.decode(encoding = 'utf8', errors = 'ignore'))
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 decoded by using decode() function and print the original string on console.
1 Ståle Straße
2 Ståle Straße
3 Ståle Straße
decode() with ascii
1 import pandas as pd
2
3 msg = 'Ståle Straße'
4
5
6 s1 = msg.encode(encoding = 'ascii', errors = 'namereplace')
7 s2 = msg.encode(encoding = 'ascii', errors = 'replace')
8 s3 = msg.encode(encoding = 'ascii', errors = 'backslashreplace')
9
10 res1 = s1.decode(encoding = 'ascii', errors = 'namereplace')
11 res2 = s2.decode(encoding = 'ascii', errors = 'replace')
12 res3 = s3.decode(encoding = 'utf8', errors = 'backslashreplace')
13 print(res1)
14 print(res2)
15 print(res3)
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 decoded by using decode() function and print the original string on console.
1 St\N{LATIN SMALL LETTER A WITH RING ABOVE}le Stra\N{LATIN SMALL LETTER SHARP S}e
2 St?le Stra?e
3 St\xe5le Stra\xdfe
Related options for your search