String encode() method in Python
The encode()
method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.
Syntax
string.encode(encoding,errors)
Parameters | Description |
---|---|
encoding | (Optional) The encoding type to be used. Default is UTF-8. Standard encodings |
errors | (Optional) Set the errors mode. Default value is strict.
|
Example 1 :
txt="Hello World" print(txt.encode()) print(txt.encode(encoding="ascii")) print(txt.encode(encoding="UTF-16"))
Output
b'Hello World' b'Hello World' b'\xff\xfeH\x00e\x00l\x00l\x00o\x00 \x00W\x00o\x00r\x00l\x00d\x00'
Example 2 : Encoding with error parameter
txt="Hellö World" print(txt.encode(encoding="ascii",errors="ignore")) print(txt.encode(encoding="ascii",errors="replace")) print(txt.encode(encoding="ascii",errors="xmlcharrefreplace")) print(txt.encode(encoding="ascii",errors="backslashreplace")) print(txt.encode(encoding="ascii",errors="namereplace"))
Output
b'Hell World' b'Hell? World' b'Hellö World' b'Hell\\xf6 World' b'Hell\\N{LATIN SMALL LETTER O WITH DIAERESIS} World'