Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Defining bytes Objects with bytes()

Give Feedback

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():

  1. bytes(<s>, <encoding>) creates a bytes object from a string.
  2. bytes(<size>) creates a bytes object consisting of null (0x00) bytes.
  3. 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

Comments & Discussion

Become a Member to join the conversation.