23
loading...
This website collects cookies to deliver better user experience
bytes()
function return an immutable byte-represented object of given size and data.bytes()
method provides immutable (cannot be changed) sequence of objects in the range of 0 <= x < 256
bytearray()
method.bytes()
method is:**bytes([source[, encoding[, errors]]])**
bytes()
method takes three optional parameters.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()
function returns an array of bytes of the given size and initializes values.# size of array
size = 6
# bytes() will create an array of given size
# and initialize with null bytes
arr = bytes(size)
print(arr)
b'\x00\x00\x00\x00\x00\x00'
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)
b'Hello World !!!'
b'\xff\xfeH\x00e\x00l\x00l\x00o\x00 \x00W\x00o\x00r\x00l\x00d\x00 \x00!\x00!\x00!\x00'
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')))
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)
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))
b'\x01\x02\x03\x04\x05'
Count of bytes: 5
bytes()
, an array of size 0 is created.# array of size 0 will be created
# iterable as source
arr = bytes()
print(arr)
b''