Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python bytes() Function

#1
Python bytes() Function

<div><p class="has-pale-cyan-blue-background-color has-background">Python’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—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>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe 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>
</div>
</figure>
<p>Here’s a minimal example that creates a <code>byte</code> from three integers stored in a list:</p>
<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])
b'\x01\x02\x03'</pre>
<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’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>
<pre class="wp-block-preformatted"><strong>Syntax: <code>bytes([source[, encoding[, errors]]])</code></strong></pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Argument</strong></td>
<td><code>source</code> (Optional)</td>
<td>Allows you to initialize the <code>byte</code> in four different ways (from simple to more complex):</p>
<p><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <em>integer</em> –> array has this size and is initialized with 0 bytes:<br />>>> <code>bytes(4)<br />b'\x00\x00\x00\x00'</code></p>
<p><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <em>iterable</em> –> 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>
<p><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <em>string</em> and you provide the <em>encoding</em> (and optionally, <em>errors</em>) arguments –> <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>
<p><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f40d.png" alt="?" 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> –> initializes the byte object via a read-only object buffer.</td>
</tr>
<tr>
<td><strong>Argument</strong></td>
<td><code>encoding</code> (Optional)</td>
<td>The encoding used in case you provide a string argument. Example: <code>'UTF-8'</code>. </td>
</tr>
<tr>
<td><strong>Argument</strong></td>
<td><code>errors</code> (Optional)</td>
<td>The action to take when the encoding conversion fails. Only makes sense if <code>source</code> argument is a string.</td>
</tr>
<tr>
<td><strong>Return Value</strong></td>
<td><code>byte</code></td>
<td>Returns a new object of type byte—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 src="https://s.w.org/images/core/emoji/13.0.0/72x72/2b50.png" alt="⭐" 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>
</tr>
</tbody>
</table>
</figure>
<p>Here are some basic usages of the function:</p>
<pre class="wp-block-preformatted"><strong>Input </strong>: <code>bytes(4)</code>
<strong>Output </strong>: <code><code>b'\x00\x00\x00\x00'</code></code> <strong>Input </strong>: <code>bytes([1, 2, 3])</code>
<strong>Output </strong>: <code><code>b'\x01\x02\x03'</code></code> <strong>Input </strong>: <code>bytes('hi', 'UTF-8')</code>
<strong>Output </strong>: <code>b'hi'</code></pre>
<p>Want to learn more? We’re going to dive into more examples next!</p>
<hr class="wp-block-separator"/>
<p><strong>But before we move on, I’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>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’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>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img 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>
</div>
<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
<h2>Create Bytes Object From Single Integer Argument — Examples </h2>
<p>The following code shows you how to use the <code>bytes()</code> function on simple integer arguments.</p>
<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
print(bytes())
print(bytes(2))
print(bytes(4)) '''
b''
b'\x00\x00'
b'\x00\x00\x00\x00' '''</pre>
<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>
<h2>Create Bytes Object From Iterable of Integers — Examples</h2>
<p>You can also provide an iterable argument to obtain a new byte object:</p>
<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
print(bytes([1, 1, 1]))
print(bytes([14]))
print(bytes({9, 8, 7})) '''
b'\x01\x01\x01'
b'\x0e'
b'\x08\t\x07' '''
</pre>
<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>
<h2>How to Fix “ValueError: byte must be in range(0, 256)”</h2>
<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>
<p>Here’s an example of the ValueError where you use a number larger or equal than 256:</p>
<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])
Traceback (most recent call last): File "&lt;pyshell#15>", line 1, in &lt;module> bytes([999])
ValueError: bytes must be in range(0, 256)</pre>
<p>Another example when using a number smaller than 0:</p>
<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])
Traceback (most recent call last): File "&lt;pyshell#16>", line 1, in &lt;module> bytes([-10])
ValueError: bytes must be in range(0, 256)</pre>
<p>Fix it by modifying the numbers to lie within the interval 0 to 256:</p>
<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])
b'\xff'</pre>
<h2>Summary</h2>
<p>Python’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>
<p><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <em>integer</em> –> array has this size and is initialized with 0 bytes:</p>
<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)
b'\x00\x00\x00\x00'</pre>
<p><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <em>iterable</em> –> integers in the range <code>0 &lt;= x &lt; 256</code> are initial byte contents:</p>
<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])
b'\x01\x02\x03'</pre>
<p><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <em>string</em> and you provide the <em>encoding</em> (and optionally, <em>errors</em>) arguments –> <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>
<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')
b'hi'</pre>
<p><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f40d.png" alt="?" 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> –&gt; initializes the byte object via a read-only object buffer.</p>
<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>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<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>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<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>
</div>


https://www.sickgaming.net/blog/2020/12/...-function/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016