Python3 Func Bytes
# Python3.x Python bytes() Function
[ Python3 Built-in Functions](#)
* * *
`bytes()` is a built-in function in Python used to create immutable byte sequences.
Byte sequences (bytes) are a fundamental data type in Python used for handling binary data, commonly used in file I/O, network transmission, image processing, and other scenarios. Bytes are immutable; once created, they cannot be modified.
**Word Definition**: `bytes` 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: Source data used to initialize the byte sequence.
* **Parameter encoding** (optional):
* Type: String
* Description: Encoding format for 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.
* **Characteristics**: Each element in bytes is an integer between 0-255.
* * *
## Examples
### Example 1: Creating bytes
## Example
# Create bytes of specified length
b =bytes(5)
print(b)# Output: b'x00x00x00x00x00'
# 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'xe4xbdxa0xe5xa5xbd'
# Using a literal
b = b"Hello"
print(b)# Output: b'Hello'
**Expected Output:**
b'x00x00x00x00x00' b'Hello' b'xe4xbdxa0xe5xa5xbd' b'Hello'
**Code Analysis:**
1. bytes(5) creates 5 zero bytes.
2. Elements of the iterable object must be integers between 0-255.
3. String conversion requires specifying the encoding format.
### Example 2: bytes Operations
## Example
# Accessing bytes
b = b"Hello"
print(b)# Output: 72
print(b)# 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 = 65 # This will raise a TypeError
**Expected Output:**
72101 b'ell'65 66 67Hello
bytes supports indexing, slicing, iteration, and other operations, but cannot modify elements.
* * Python3 Built-in Functions](#)
* * *
YouTip