Python String encode
Now, we are going to learn about the encoding method. As the name of the method suggests, it is going to return an encoded version of the string, as a bytes object. The default encoding is ‘utf – 8’.
Let’s have a look at a simple program, which demonstrates the same thing.
Python String encode() Method
As you can see in the above program, we have a string, and then we are calling the encode method, which returns the encoded version of the string, as a bytes object. Let’s have a look at the output now –
b’Hello from GyaniPandit’
As you can see that we have the encoded string as a bytes object. So, as and when required, we can make use of the encode method in relation to the string in python. We can provide the encoding as an argument to the encoding method, but the default is ‘utf – 8’. Another popular encoding that you might be familiar with is ascii, and there are some others as well.
Also, we can specify another argument, as errors, which defaults to ‘strict’. It is the response when the encoding fails. There are different values for this argument, like ‘strict’, ‘ignore’, ‘replace’ etc…
- The argument value ‘strict’ specifies that if the encoding fails, it raises an UnicodeDecodeError.
- The argument value ‘ignore’ ignores the unencodable Unicode from the result.
- The argument value ‘replace’ replaces the unencodable Unicode with a question mark(?).
So, as and when required, we can make use of the encoding method. Remember that this method returns the encoded version of the string, as a bytes object. You can also check the type of the return value from the encode method. We can also specify the encoding, and the default is ‘utf – 8’.