What Is Bytes() In Python?

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeWhat 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 Python

Parameters and return value

The return value of the bytes() function varies in two ways depending upon the parameters:

  1. If an integer indicating the size of the bytes is passed into the function, it returns an empty bytes object of the specified size.

  2. 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.

  3. 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)Run

Here, 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)Run

Similarly, 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)Run

Relevant 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'