Python bytes() Function
bytes()It is a built-in function in Python used to create immutable byte sequences.
Byte sequences (bytes) are a fundamental type in Python for handling binary data, commonly used in file reading/writing, network transmission, image processing, and other scenarios. bytes is immutable and cannot be modified after creation.
Word Definition: bytesIt means "byte" and is a binary data type in Python.
Basic Syntax and Parameters
Syntax Format
bytes(source) bytes(source, encoding) bytes(source, encoding, errors)
Parameter Description
- Parameter source:
- Type: integer, iterable object, string
- Description: The source data used to initialize the byte sequence.
- Parameter encoding(Optional):
- Type: string
- Description: The encoding format of the string (e.g., 'utf-8').
- Parameter errors(Optional):
- Type: string
- Description: Error handling method for encoding.
Function Description
- Return value: Returns an immutable bytes object.
- Features: Each element in bytes is an integer from 0 to 255.
Examples
Example 1: Creating bytes
Examples
# Create bytes of specified length
b = bytes(5)
print(b) # Output: b'\x00\x00\x00\x00\x00'
# Create from an iterable object
b = bytes([72, 101, 108, 108, 111])
print(b) # Output: b'Hello'
# Create from a string (requires encoding)
b = bytes(Hello, encoding='utf-8')
print(b) # Output: b'\xe4\xbd\xa0\xe5\xa5\xbd'
# Use literal
b = b"Hello"
print(b) # Output: b'Hello'
b = bytes(5)
print(b) # Output: b'\x00\x00\x00\x00\x00'
# Create from an iterable object
b = bytes([72, 101, 108, 108, 111])
print(b) # Output: b'Hello'
# Create from a string (requires encoding)
b = bytes(Hello, encoding='utf-8')
print(b) # Output: b'\xe4\xbd\xa0\xe5\xa5\xbd'
# Use literal
b = b"Hello"
print(b) # Output: b'Hello'
Expected output:
b'\x00\x00\x00\x00\x00' b'Hello' b'\xe4\xbd\xa0\xe5\xa5\xbd' b'Hello'
Code explanation:
- bytes(5) creates 5 zero bytes.
- Elements of an iterable object must be integers from 0 to 255.
- String conversion requires specifying an encoding format.
Example 2: bytes Operations
Examples
# Access bytes
b = b"Hello"
print(b[0]) # Output: 72
print(b[1]) # Output: 101
# Slicing
print(b[1:4]) # b'ell'
# Iteration
for byte in b"ABC":
print(byte, end=" ")
print() # Output: 65 66 67
# Convert back to string
b = b"Hello"
s = b.decode('utf-8')
print(s) # Output: Hello
# bytes is immutable
# b
b = b"Hello"
print(b[0]) # Output: 72
print(b[1]) # Output: 101
# Slicing
print(b[1:4]) # b'ell'
# Iteration
for byte in b"ABC":
print(byte, end=" ")
print() # Output: 65 66 67
# Convert back to string
b = b"Hello"
s = b.decode('utf-8')
print(s) # Output: Hello
# bytes is immutable
# b
Expected output:
72 101 b'ell' 65 66 67 Hello
bytes supports indexing, slicing, iteration, and other operations, but its elements cannot be modified.
Other Extensions
Python3 Built-in Functions