Python String to Bytes: Conversion Methods
Learn how to convert Python strings to bytes with encode() and bytes(), handle encoding errors, and choose the right approach for your data.

When you need to convert a Python string to bytes, the standard library gives you two primary tools: the str.encode() method and the bytes() constructor. Both produce a bytes object, but they differ mainly in syntax and in how you supply the encoding. Understanding these differences matters because the choice affects code clarity and how you manage non-ASCII text and encoding errors.
The Two Main Ways to Convert a String to Bytes
The most common way to convert a string to bytes is to call .encode() on the string object. This method returns a bytes representation using a specified encoding, defaulting to UTF-8. The bytes() constructor can also create a bytes object from a string, but it requires you to pass the string and an encoding as arguments.
# Using encode()
text = "hello"
b1 = text.encode() # b'hello'
# Using bytes()
b2 = bytes(text, "utf-8") # b'hello'Both approaches yield the same result for a simple ASCII string. The syntax difference matters because bytes() requires an explicit encoding, while encode() defaults to UTF-8. Both methods also accept an errors argument for controlling what happens when a character cannot be encoded.
How encode() Works
The encode() method is defined on str objects. It takes an optional encoding parameter and an optional errors parameter. If you omit the encoding, Python assumes UTF-8, which is the modern default for text interchange.
s = "café"
b = s.encode("utf-8") # b'caf\xc3\xa9'You can also use other encodings like "latin-1" or "ascii", but you must ensure the string contains only characters representable in that encoding. If a character cannot be encoded, Python raises a UnicodeEncodeError unless you specify an error-handling strategy.
The errors parameter accepts values such as "strict" (default), "ignore", "replace", and "backslashreplace". For example, "replace" substitutes an unencodable character with a question mark, which is useful when you cannot lose data but do not want the program to crash.
s = "café"
b = s.encode("ascii", errors="replace") # b'caf?'Using bytes() to Create a Bytes Object
The bytes() constructor can take a string as its first argument, but it requires a second argument specifying the encoding. This mirrors the encode() behavior, but the syntax is less direct. It is often used when you already have an encoding variable or when you want to emphasize that the result is a new bytes object.
encoding = "utf-8"
b = bytes("hello", encoding)A common mistake is to call bytes("hello") without the encoding. This raises a TypeError because Python cannot guess the encoding from the string alone. Always provide an explicit encoding when using bytes() with a string.
You can also create a bytes object from an iterable of integers, but that is a different operation and not directly related to string conversion. For string-to-bytes conversion, the constructor and the encode() method are functionally equivalent when the same encoding and error handling are used.
Handling Encoding Errors Gracefully
Encoding errors occur when a character in the string cannot be represented in the target encoding. The default behavior is strict, meaning the operation raises an exception. In many real-world applications, you need to decide how to handle such cases.
The errors parameter gives you control. For example, "ignore" drops the unencodable characters, which can lead to silent data loss. "replace" substitutes a placeholder like ?, preserving the length but not the original content. "backslashreplace" uses a backslash escape sequence, which preserves the code point information for debugging purposes.
s = "café"
print(s.encode("ascii", errors="backslashreplace")) # b'caf\\xe9'If you are writing data to a file or network socket, consider using "strict" and catching UnicodeEncodeError explicitly. This makes the failure point visible and avoids silently corrupting data.
Performance and Memory Considerations
Converting a string to bytes is not free. It allocates a new bytes object and copies the character data, applying the encoding transformation. For small strings, this overhead is negligible, but in tight loops or when processing large text, it can add up.
A common performance pitfall is repeatedly encoding the same string. If you need the same bytes multiple times, compute them once and reuse the result. This is especially relevant in network protocols or when writing to a file in chunks.
Memory usage also matters if you keep many encoded values. A bytes object holds the encoded representation, and the number of bytes per code point depends on the encoding: UTF-8 uses one to four bytes per code point, while UTF-16 uses either two or four bytes per code point. If memory is constrained, choose an encoding that fits the characters you are storing.
Compatibility Notes for Python 2 and 3
Python 2 had a different model: str was a byte sequence, and unicode was the text type. In Python 3, str is always text, and bytes is a separate binary type. This change means that code written for Python 2 often mixes the two incorrectly.
If you are maintaining legacy code, be aware that u"text" in Python 2 is equivalent to "text" in Python 3. The encode() method exists on unicode in Python 2 and on str in Python 3, but the semantics are consistent. For new code, target Python 3 and use str for text and bytes for binary data.
When working with libraries that return bytes (such as socket.recv() or os.read()), you must decode them back to str using the same encoding. The reverse operation is .decode(), which completes the round trip.
Choosing Between encode() and bytes()
Both methods produce identical results when given the same encoding and error handling. The choice often comes down to readability and intent. encode() reads naturally when you are thinking of the string as the primary object. bytes() is useful when you are constructing a bytes object from multiple sources or when the encoding is stored in a variable.
A practical guideline: use encode() when you are converting a known string variable to bytes for I/O. Use bytes() when you are creating a bytes object as part of a larger expression, or when you want to make the encoding explicit at the call site.
# Clear intent
payload = message.encode("utf-8")
# Explicit encoding variable
enc = "utf-8"
payload = bytes(message, enc)For the same encoding and error handling, the two forms are functionally equivalent. The real decision is about code clarity and maintainability. Choose the form that makes the conversion obvious to the next developer reading the code.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.