Python Reference Β· Numbers and Binary Data
Python bytes and bytearray methods
Reference for bytes and bytearray methods: decode(), hex(), fromhex(), split(), join(), find(), replace(), strip(), plus the mutating bytearray methods.
bytes (immutable) and bytearray (mutable) share almost the same method set. Many of them mirror string methods (split, replace, strip, startswith, find...), but they work on integers 0-255 and take bytes-like arguments, never str. A few are special: decode() turns bytes into text, hex() and fromhex() convert to and from hexadecimal, and bytearray adds in-place methods such as append() and extend().
Methods on bytes return new bytes; the same methods on bytearray return new bytearray objects and leave the original unchanged, except the mutating ones listed below.
b"a,b".split(b",") # [b'a', b'b'] b"Hi".hex() # '4869' bytes.fromhex("4869") # b'Hi'
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
| Method | Description |
|---|---|
b.decode(encoding="utf-8", errors="strict") |
Return a str. errors can be "strict", "ignore", "replace", "backslashreplace" and more. |
b.hex(sep=None, bytes_per_sep=1) |
Return a hexadecimal str of the bytes, with an optional separator. |
bytes.fromhex(s) / bytearray.fromhex(s) |
Class method: build from a hex string; ASCII whitespace is ignored. |
split, rsplit, splitlines, partition, rpartition |
Break into pieces, like the str versions. |
join(iterable) |
Join bytes-like items using b as the separator. |
find, rfind, index, rindex, count, startswith, endswith |
Searching. find returns -1 when missing, index raises ValueError. |
replace, strip, lstrip, rstrip, removeprefix, removesuffix |
Return modified copies. |
upper, lower, title, capitalize, swapcase |
ASCII-only case mapping. |
isalpha, isdigit, isalnum, isspace, isupper, islower, isascii |
ASCII-only tests. |
ljust, rjust, center, zfill, expandtabs |
Padding. |
translate(table, delete=b""), bytes.maketrans(a, b) |
Byte-for-byte mapping. |
bytearray only: append, extend, insert, pop, remove, reverse, clear, copy |
In-place edits (copy returns a new bytearray). |
Raises: TypeError when a method receives a str where bytes are required; ValueError for invalid hex digits in fromhex or a value outside 0-255; UnicodeDecodeError from decode() when the bytes are not valid in the chosen encoding.
Usage notes
- Never mix
strandbytes.b"a" + "b"andb"a" == "a"do not do what you expect (the comparison is justFalse). Encode or decode explicitly. - ASCII only. Case and
is...methods affect only ASCII letters; non-ASCII bytes are left alone. Decode tostrfor real Unicode handling. - Indexing gives integers, slicing gives bytes:
b"AB"[0]is65,b"AB"[0:1]isb'A'. bytesis immutable. Code likedata[0] = 1fails withTypeError. Usebytearrayfor in-place edits, ormemoryviewfor zero-copy slices.decode()defaults to strict UTF-8, so unexpected input raises. Useerrors="replace"when you only need a readable approximation, and never silentlyignoredata you must keep intact.hex()with a separator works from the right whenbytes_per_sepis positive and from the left when it is negative.- Joining:
b"".join(chunks)is the fast way to build onebytesfrom many; repeated+=onbytescopies every time.
Related
bytes(),bytearray(),memoryview,str.encode()struct,base64- Lessons: Strings, Files