{"id":121717,"date":"2020-12-07T16:47:56","date_gmt":"2020-12-07T16:47:56","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=17964"},"modified":"2020-12-07T16:47:56","modified_gmt":"2020-12-07T16:47:56","slug":"python-bytes-function","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/12\/07\/python-bytes-function\/","title":{"rendered":"Python bytes() Function"},"content":{"rendered":"<p class=\"has-pale-cyan-blue-background-color has-background\">Python&#8217;s built-in <code>bytes(source)<\/code> function creates an immutable <code>bytes<\/code> object initialized as defined in the function argument <code>source<\/code>. A bytes object is like a string but it uses only byte characters consisting of a sequence of 8-bit integers in the range <code>0&lt;=x&lt;256<\/code>. The returned byte object is immutable&#8212;you cannot change it after creation. If you plan to change the contents, use the <code><a href=\"https:\/\/blog.finxter.com\/python-bytearray-function\/\" title=\"Python bytearray() Function\" target=\"_blank\" rel=\"noreferrer noopener\">bytearray()<\/a><\/code> method to create a mutable <code>bytearray<\/code> object. <\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"Python bytes() | Complete Guide\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/b4PRIyk33WY?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>Here&#8217;s a minimal example that creates a <code>byte<\/code> from three integers stored in a list:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> bytes([1, 2, 3])\nb'\\x01\\x02\\x03'<\/pre>\n<p>The prefix <code>\\x<\/code> escape sequence means the next two characters are interpreted as hex character codes. For instance, the hex code <code>\\x01<\/code> is the same as <code>chr(0x01)=16*0+1=1<\/code> that&#8217;s simply a start of heading <code>SOH<\/code> character. (<a href=\"https:\/\/stackoverflow.com\/questions\/2672326\/what-does-a-leading-x-mean-in-a-python-string-xaa\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/stackoverflow.com\/questions\/2672326\/what-does-a-leading-x-mean-in-a-python-string-xaa\">source<\/a>, <a href=\"https:\/\/blog.finxter.com\/ascii-table\/\" title=\"ASCII Table\" target=\"_blank\" rel=\"noreferrer noopener\">ASCII table<\/a>)<\/p>\n<pre class=\"wp-block-preformatted\"><strong>Syntax: <code>bytes([source[, encoding[, errors]]])<\/code><\/strong><\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><strong>Argument<\/strong><\/td>\n<td><code>source<\/code> (Optional)<\/td>\n<td>Allows you to initialize the <code>byte<\/code> in four different ways (from simple to more complex):<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <em>integer<\/em> &#8211;> array has this size and is initialized with 0 bytes:<br \/>>>> <code>bytes(4)<br \/>b'\\x00\\x00\\x00\\x00'<\/code><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <em>iterable<\/em> &#8211;> integers in the range <code>0 &lt;= x &lt; 256<\/code> are initial byte contents:<br \/>>>> <code>bytes([1, 2, 3])<br \/>b'\\x01\\x02\\x03'<\/code><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/>\u00a0<em>string<\/em> and you provide the <em>encoding<\/em> (and optionally, <em>errors<\/em>) arguments &#8211;> <code>bytes()<\/code> converts string to bytes using <a href=\"https:\/\/docs.python.org\/3\/library\/stdtypes.html#str.encode\"><code>str.encode()<\/code><\/a>:<br \/><code>>>> bytes('hi', 'UTF-8')<br \/>b'hi'<\/code><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <em>object <\/em>implementing the <a href=\"https:\/\/docs.python.org\/3\/c-api\/buffer.html#bufferobjects\">buffer interface<\/a> &#8211;> initializes the byte object via a read-only object buffer.<\/td>\n<\/tr>\n<tr>\n<td><strong>Argument<\/strong><\/td>\n<td><code>encoding<\/code> (Optional)<\/td>\n<td>The encoding used in case you provide a string argument. Example: <code>'UTF-8'<\/code>. <\/td>\n<\/tr>\n<tr>\n<td><strong>Argument<\/strong><\/td>\n<td><code>errors<\/code> (Optional)<\/td>\n<td>The action to take when the encoding conversion fails. Only makes sense if <code>source<\/code> argument is a string.<\/td>\n<\/tr>\n<tr>\n<td><strong>Return Value<\/strong><\/td>\n<td><code>byte<\/code><\/td>\n<td>Returns a new object of type byte&#8212;a sequence of bytes that is immutable. For a mutable version, consider using the <code><a href=\"https:\/\/blog.finxter.com\/python-bytearray-function\/\" title=\"Python bytearray() Function\">bytearray()<\/a><\/code> function.<br \/><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/2b50.png\" alt=\"\u2b50\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> Without an optional argument, it returns a byte object with one byte 0:<br \/><code>>>> bytes()<br \/>b''<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>Here are some basic usages of the function:<\/p>\n<pre class=\"wp-block-preformatted\"><strong>Input <\/strong>: <code>bytes(4)<\/code>\n<strong>Output <\/strong>: <code><code>b'\\x00\\x00\\x00\\x00'<\/code><\/code> <strong>Input <\/strong>: <code>bytes([1, 2, 3])<\/code>\n<strong>Output <\/strong>: <code><code>b'\\x01\\x02\\x03'<\/code><\/code> <strong>Input <\/strong>: <code>bytes('hi', 'UTF-8')<\/code>\n<strong>Output <\/strong>: <code>b'hi'<\/code><\/pre>\n<p>Want to learn more? We&#8217;re going to dive into more examples next!<\/p>\n<hr class=\"wp-block-separator\"\/>\n<p><strong>But before we move on, I&#8217;m excited to present you my brand-new Python book <a rel=\"noreferrer noopener\" href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" title=\"https:\/\/amzn.to\/2WAYeJE\">Python One-Liners<\/a><\/strong> (Amazon Link).<\/p>\n<p>If you like one-liners, you&#8217;ll LOVE the book. It&#8217;ll teach you everything there is to know about a <strong>single line of Python code.<\/strong> But it&#8217;s also an <strong>introduction to computer science<\/strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!<\/em><\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" loading=\"lazy\" width=\"215\" height=\"283\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/02\/image-1.png\" alt=\"\" class=\"wp-image-5969\"\/><\/a><\/figure>\n<\/div>\n<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). <\/p>\n<p>Link: <a href=\"https:\/\/nostarch.com\/pythononeliners\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/nostarch.com\/pythononeliners<\/a><\/p>\n<h2>Create Bytes Object From Single Integer Argument &#8212; Examples <\/h2>\n<p>The following code shows you how to use the <code>bytes()<\/code> function on simple integer arguments.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Single Integer Input Argument\nprint(bytes())\nprint(bytes(2))\nprint(bytes(4)) '''\nb''\nb'\\x00\\x00'\nb'\\x00\\x00\\x00\\x00' '''<\/pre>\n<p>If you provide only one input argument, it uses this input argument to determine how many bytes should be created. It just uses bytes with value 0, in byte notation <code>x00<\/code> to fill the <code>byte<\/code>.<\/p>\n<h2>Create Bytes Object From Iterable of Integers &#8212; Examples<\/h2>\n<p>You can also provide an iterable argument to obtain a new byte object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Iterable Input Argument\nprint(bytes([1, 1, 1]))\nprint(bytes([14]))\nprint(bytes({9, 8, 7})) '''\nb'\\x01\\x01\\x01'\nb'\\x0e'\nb'\\x08\\t\\x07' '''\n<\/pre>\n<p>The iterable must consist of a number of integers between 0 and 256. If you fail to do so, Python will throw a ValueError:<\/p>\n<h2>How to Fix &#8220;ValueError: byte must be in range(0, 256)&#8221;<\/h2>\n<p class=\"has-pale-cyan-blue-background-color has-background\">If you use the <code>bytes()<\/code> function on an iterable that contains at least one integer greater than the maximum number representable by 8 bits, namely 256, or smaller than 0, Python will throw a <code>ValueError: byte must be in range(0, 256)<\/code>. You can fix it by ensuring that each number in your iterable can actually be represented by 8 bits and falls into the interval 0 to 256. <\/p>\n<p>Here&#8217;s an example of the ValueError where you use a number larger or equal than 256:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> bytes([999])\nTraceback (most recent call last): File \"&lt;pyshell#15>\", line 1, in &lt;module> bytes([999])\nValueError: bytes must be in range(0, 256)<\/pre>\n<p>Another example when using a number smaller than 0:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> bytes([-10])\nTraceback (most recent call last): File \"&lt;pyshell#16>\", line 1, in &lt;module> bytes([-10])\nValueError: bytes must be in range(0, 256)<\/pre>\n<p>Fix it by modifying the numbers to lie within the interval 0 to 256:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> bytes([255])\nb'\\xff'<\/pre>\n<h2>Summary<\/h2>\n<p>Python&#8217;s built-in function <code>bytes()<\/code> allows you to initialize the <code>byte<\/code> in four different ways (from simple to more complex):<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <em>integer<\/em> &#8211;> array has this size and is initialized with 0 bytes:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> bytes(4)\nb'\\x00\\x00\\x00\\x00'<\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <em>iterable<\/em> &#8211;> integers in the range <code>0 &lt;= x &lt; 256<\/code> are initial byte contents:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> bytes([1, 2, 3])\nb'\\x01\\x02\\x03'<\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/>\u00a0<em>string<\/em> and you provide the <em>encoding<\/em> (and optionally, <em>errors<\/em>) arguments &#8211;> <code>bytes()<\/code> converts string to bytes using <a href=\"https:\/\/docs.python.org\/3\/library\/stdtypes.html#str.encode\"><code>str.encode()<\/code><\/a>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> bytes('hi', 'UTF-8')\nb'hi'<\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <em>object <\/em>implementing the <a href=\"https:\/\/docs.python.org\/3\/c-api\/buffer.html#bufferobjects\">buffer interface<\/a> &#8211;&gt; initializes the byte object via a read-only object buffer.<\/p>\n<p>Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!<\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?<\/p>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<p>The post <a href=\"https:\/\/blog.finxter.com\/python-bytes-function\/\" target=\"_blank\" rel=\"noopener noreferrer\">Python bytes() Function<\/a> first appeared on <a href=\"https:\/\/blog.finxter.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">Finxter<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python&#8217;s built-in bytes(source) function creates an immutable bytes object initialized as defined in the function argument source. A bytes object is like a string but it uses only byte characters consisting of a sequence of 8-bit integers in the range 0&lt;=x&lt;256. The returned byte object is immutable&#8212;you cannot change it after creation. If you plan [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-121717","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/121717","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=121717"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/121717\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=121717"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=121717"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=121717"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}