ItsMyCode |
Python bytes()
function return an immutable byte-represented object of given size and data.
The bytes()
method provides immutable (cannot be changed) sequence of objects in the range of 0 <= x < 256
If you want a mutable version, you can use the bytearray()
method.
bytes() Syntax
The syntax of the bytes()
method is:
**bytes([source[, encoding[, errors]]])**
bytes() Parameters
The bytes()
method takes three optional parameters.
- source (Optional) – Initializes the array of bytes
- encoding (Optional) – in case if the source is a string, the encoding of the string.
- errors (Optional) – An action to take if the encoding conversion fails.
The source parameter can be of any below type as follows.
Type | Description |
---|---|
String | Converts the given string into bytes using str.encode() . In the case of a string, you must also pass encoding as an argument and, optionally errors
|
Integer | Creates an array of provided size and initializes with null bytes |
Object | A read-only buffer of the object will be used to initialize the byte array |
Iterable | Creates an array of size equal to the iterable count and initialized to the iterable elements. The iterable should be of integers and the range should be in between 0 <= x < 256
|
No source (arguments) | An array of size 0 is created. |
bytes() Return Value
The bytes()
function returns an array of bytes of the given size and initializes values.
Example 1: Create a byte of a given integer size
In the case of an integer, it creates an array of provided size and initializes with null bytes.
# size of array
size = 6
# bytes() will create an array of given size
# and initialize with null bytes
arr = bytes(size)
print(arr)
Output
b'\x00\x00\x00\x00\x00\x00'
Example 2: Convert string to bytes
Converts the given string into bytes using str.encode()
. In the case of a string, you must also pass encoding as an argument and, optionally, errors.
# string declaration
string = "Hello World !!!"
# string with encoding 'utf-8'
arr1 = bytes(string, 'utf-8')
print(arr1)
# string with encoding 'utf-16'
arr2 = bytes(string, 'utf-16')
print(arr2)
Output
b'Hello World !!!'
b'\xff\xfeH\x00e\x00l\x00l\x00o\x00 \x00W\x00o\x00r\x00l\x00d\x00 \x00!\x00!\x00!\x00'
The string handling error is defined as:
*String Error Handlers : *
- strict: ** Raises the default **UnicodeDecodeError in case of encoding failure.
- *ignore: * Ignores the unencodable character and encodes the remaining string.
- *replace: * Replaces the unencodable character with a ‘?’.
If you notice the strict type will raise an UnicodeEncodeError if the encoding fails as shown below.
from typing import Text
text = 'HellÖ WÖrld'
# Giving ascii encoding and ignore error
print("Byte conversion with ignore error : " +
str(bytes(text, 'ascii', errors='ignore')))
# Giving ascii encoding and replace error
print("Byte conversion with replace error : " +
str(bytes(text, 'ascii', errors='replace')))
# Giving ascii encoding and strict error throws exception
print("Byte conversion with strict error : " +
str(bytes(text, 'ascii', errors='strict')))
python
Output
Byte conversion with ignore error : b'Hell Wrld'
Byte conversion with replace error : b'Hell? W?rld'
Traceback (most recent call last):
File "c:\Projects\Tryouts\main.py", line 17, in <module>
str(bytes(text, 'ascii', errors='strict')))
UnicodeEncodeError: 'ascii' codec can't encode character '\xd6' in position 4: ordinal not in range(128)
Example 3: Convert iterable list to bytes
Creates an array of size equal to the iterable count and initialized to the iterable elements. The iterable should be of integers, and the range should be in between 0 <= x < 256
# list of integers
lst = [1, 2, 3, 4, 5]
# iterable as source
arr = bytes(lst)
print(arr)
print("Count of bytes:", len(arr))
Output
b'\x01\x02\x03\x04\x05'
Count of bytes: 5
Example 4: If no source is passed to bytes()
If no source is passed into bytes()
, an array of size 0 is created.
# array of size 0 will be created
# iterable as source
arr = bytes()
print(arr)
Output
b''
The post Python bytes() appeared first on ItsMyCode.
Top comments (0)