In the last lesson, you saw how you could create a bytes
object using a string literal with the addition of a 'b'
prefix. In this lesson, you’ll learn how to use bytes()
to create a bytes
object. You’ll explore three different forms of using bytes()
:
bytes(<s>, <encoding>)
creates a bytes object from a string.bytes(<size>)
creates a bytes object consisting of null (0x00) bytes.bytes(<iterable>)
creates a bytes object from an iterable.
Here’s how to use bytes(<s>, <encoding>)
:
>>> a = bytes('bacon and egg', 'utf8')
>>> a
b'bacon and egg'
>>> type(a)
<class 'bytes'>
>>> b = bytes('Hello ∑ €', 'utf8')
>>> b
b'Hello \xe2\x88\x91 \xe2\x82\xac'
>>> len(a)
13
>>> a
b'bacon and egg'
>>> b
b'Hello \xe2\x88\x91 \xe2\x82\xac'
>>> len(b)
13
>>> a[0]
98
>>> a[1]
97
>>> a[2]
99
>>> b[0]
72
>>> b[1]
101
>>> b[5]
32
>>> b[6]
226
>>> b[7]
136
>>> b[8]
145
Here’s how to use bytes(<size>)
:
>>> c = bytes(8)
>>> c
b'\x00\x00\x00\x00\x00\x00\x00\x00'
>>>len(c)
8
Here’s how to use bytes(<iterable>)
:
>>> d = bytes([115, 112, 97, 109, 33])
>>> d
b'spam!'
>>> type(d)
<class 'bytes'>
>>> d[0]
115
>>> d[3]
109
theramstoss on June 4, 2020
Question for you: why does bytes(‘\x80’, ‘utf8’) evaluate to b’\xc2\x80’ ?
Thank you!