What Is Bytes() In Python?
The bytes() function converts an object (such as a list, string, integers, etc.) into an immutable bytes object within the range of 0 to 256. If no object is provided to the bytes() method, it can generate an empty bytes object of a specified size.
Syntax
This method can be declared in two ways, depending on the requirement:
The two types of syntaxes of bytes() method in PythonParameters and return value
The return value of the bytes() function varies in two ways depending upon the parameters:
-
If an integer indicating the size of the bytes is passed into the function, it returns an empty bytes object of the specified size.
-
Instead of a size, a string, tuple, or a list is passed into the bytes() method, it is converted into a corresponding bytes object. In this case, the encoding for the string, tuple, or list can be specified, and hence encoding is an optional parameter.
-
A third optional argument is passed in the function that tells what to do if the method fails to cater to the errors.
Code
An empty bytes object of a specific size is created in the example below, i.e., 6.
# specify sizesize = 6#generate empty bytes object of size 6: byteArray = bytes(size)# output: b'\x00\x00\x00\x00\x00\x00'print(byteArray)RunHere, no specific size of the required bytes is given because an object, i.e., string, is passed into the function. Also, the encoding method “utf-8” is provided in the given instance:
givenString = ["Welcome", "to", "educative"]# given_string is encoded into bytes object according to utf-8byteArray = bytes(givenString,'útf-8')# output: b'Welcome to educatve'print(byteArray)RunSimilarly, an object, in this case, a tuple is passed into the bytes() function to generate bytes object corresponding to it without mentioning any encoding type.
tup = (1, 2, 3, 4, 5)# tuple is converted into bytes object without specifying any encoding typebyteArray = byte(tup)# outputs: b'\x01\x02\x03\x04\x05'print(byteArray)RunRelevant Answers
Explore Courses
Free Resources
License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)Từ khóa » B' X01 X02 X03 X00'
-
Convert String To Packed Hex ( '01020304' -> '\x01\x02\x03\x04' )
-
Python: Bytes() Function - W3resource
-
Python Bytes, Bytearray - W3resource
-
Python Bytes() Method (With Examples) - TutorialsTeacher
-
Types - Borsh-construct
-
Binary - Micro-IP Inc.
-
Miscellaneous — Construct 2.10 Documentation - Read The Docs
-
[PDF] Python Built-In Functions
-
Introducing Python - Manualzz
-
*Python*.txt · GitHub
-
Python Bytes() Method - GeeksforGeeks
-
Python Bytes() Function
-
Python Bytearray() - Programiz