Python String Encoding Example: UTF-8 Encode
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This code demonstrates the use of the encode() method in Python to convert a string into bytes. The string "My name is Ståle" contains a non-ASCII character (å), which is encoded into two bytes under the default UTF-8 encoding.
The output is a bytes object displayed with a b prefix, like:
b'My name is St\xc3\xa5le'Usage notes:
- Call
encode()on the string. - You can optionally specify an encoding like
'utf-16'. - Encoding to bytes is useful for writing to files or network transmission.