Python String encode() Method
Returns an encoded version of a string.
Syntax
Python
Copy Code
string.encode(encoding, errors = "strict")
Parameters
Parameter | Description |
---|---|
encoding |
Optional. The encoding to use. The default is 'UTF-8' See https://docs.python.org/3/library/codecs.html#standard-encodings for all the supported encoding schemes. |
errors |
Optional. You can tell the encode method how to handle errors, which includes:
|
Python strings are stored as Unicode, which is a format that uses one byte for the characters with character codes between 0 and 128, and up to four bytes for other characters. Unicode is the dominant encoding on the World Wide Web. The encode
method can be used to return the string with different encoding schemes. A common encoding scheme is ASCII.
Example
Python
Copy Code
str = 'The quick brown fox jumped over the lazy dog' binaryEncoded = str.encode() print(binaryEncoded) asciiEncoded = str.encode('ascii') print(asciiEncoded)
Output
b'The quick brown fox jumped over the lazy dog' b'The quick brown fox jumped over the lazy dog'
Notice how you can't tell what the encoding scheme is with the print function, but you get a clue that it's encoded because the string is prefaced with a "b" to indicate that the string is a sequence of octets — 8 bit characters.
Example
Python
Copy Code
delta = '\u0394' print(delta) encoded = delta.encode('ascii', 'replace') print(encoded)
Output
Δ b'?'