Python Reference · Built-in Functions
Python bytes() function
Reference for Python bytes(): create immutable byte sequences from a size, integers, a string with an encoding or a buffer, and convert to and from text.
bytes is the immutable sequence type for raw binary data: each item is an integer from 0 to 255. Files opened in binary mode, network packets, hashes and encoded text are all bytes.
Besides the literal form b"abc" (ASCII characters only), you can call bytes() to build one from a size, a list of integers, a string with an encoding, or another buffer.
bytes([72, 105]) # b'Hi' "café".encode("utf-8") # b'caf\xc3\xa9'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
bytes() bytes(size) bytes(iterable_of_ints) bytes(string, encoding) bytes(string, encoding, errors) bytes(buffer)
| Name | Description |
|---|---|
size |
A non-negative int: that many zero bytes. |
iterable_of_ints |
Integers in the range 0-255. |
string |
A str; needs encoding. |
encoding |
A codec name such as "utf-8", "ascii", "latin-1". |
errors |
"strict" (default), "ignore", "replace", "backslashreplace", ... |
buffer |
Any object supporting the buffer protocol (bytes, bytearray, memoryview, ...). |
Return value: a new immutable bytes object.
Raises: TypeError for a string without an encoding or an unsupported type; ValueError for integers outside 0-255.
Usage notes
- Indexing gives integers.
b"abc"[0]is97; slicing givesbytes. Useb"abc"[0:1]to get a one-bytebytes. - Literals are ASCII only.
b"café"is a syntax error. Encode astrinstead. bytes(5)is five zero bytes, not the text"5". Usestr(5).encode()for that.- Encoding vs decoding.
str.encode()produces bytes;bytes.decode()produces text. Always name the encoding when files or protocols are involved, and prefer UTF-8. - Immutable and hashable. You can use
bytesas a dictionary key. For in-place edits usebytearray. - Helpful methods.
hex(),bytes.fromhex(),split,replace,startswith,find, andint.from_bytes()/int.to_bytes()for numbers. str(b"x")is a repr, not a decode.str(b"hi")returns"b'hi'". Call.decode().- Mixing types.
b"a" + "b"raisesTypeError; keep bytes and text apart.
Related
bytearray(),memoryview(),str.encode(),str(),hex()- Lessons: Strings, Files, Data types