{"id":24558,"date":"2021-10-21T10:08:35","date_gmt":"2021-10-21T04:38:35","guid":{"rendered":"https:\/\/python-programs.com\/?p=24558"},"modified":"2021-11-05T19:37:57","modified_gmt":"2021-11-05T14:07:57","slug":"python-bytes-function-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-bytes-function-with-examples\/","title":{"rendered":"Python bytes() Function with Examples"},"content":{"rendered":"

In the previous article, we have discussed Python Program for bool() Function<\/a>
\nbytes() Function in Python:<\/strong><\/p>\n

The bytes() function returns an object of type bytes.<\/p>\n

The bytes() method returns a bytes object, which is an immutable (cannot be changed) sequence of integers ranging from 0 to 256.<\/p>\n

It can either convert objects to bytes objects or create an empty bytes object of the specified size.<\/p>\n

The distinction between bytes() and bytearray() is that bytes() return an object that cannot be modified, whereas bytearray() returns a modifiable object.<\/p>\n

Syntax:<\/strong><\/p>\n

bytes(x, encoding, error)<\/pre>\n

Parameters<\/strong><\/p>\n

x:<\/strong> When creating the bytes object, this is the source that will be used.<\/p>\n

If it is an integer, it will generate an empty bytes object of the specified size.<\/p>\n

If it’s a String, make sure to specify the source’s encoding.<\/p>\n

encoding(optional):<\/strong> The string’s encoding.<\/p>\n

error(optional):<\/strong> Specifies what should happen if the encoding fails.<\/p>\n

Return Value:<\/strong><\/p>\n

The bytes() method returns bytes object with the specified size and initialization parameters.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given number = 6<\/pre>\n

Output:<\/strong><\/p>\n

The result after applying the bytes() method to the given number 6 = b'\\x00\\x00\\x00\\x00\\x00\\x00'<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given string =  \"welcome to Python-programs\"<\/pre>\n

Output:<\/strong><\/p>\n

The result after applying\u00a0the bytes() method to the given string = b'welcome to Python-programs'<\/pre>\n

Program for bytes() Function in Python<\/h2>\n