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.
Hint: You can set the default subtitles language 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 a Literal bytes Object

Give Feedback

In this lesson, you’ll practice making a literal bytes object. A bytes literal is defined in the same way as a string literal with the addition of a 'b' prefix.

Single, double, or triple quoting mechanisms can be used. Only ASCII characters are allowed, and any character value greater than 127 must be specified using an appropriate escape sequence. The 'r' prefix can be used to disable processing of escape sequences:

>>>
>>> a = b'spam egg bacon'
>>> a
b'spam egg bacon'
>>> type(a)
<class 'bytes'>

>>> c = b"Contain embedded 'single' quotes"
>>> c
b"Contain embedded 'single' quotes"
>>> type(c)
<class 'bytes'>

>>> t = b'''This bytes object contains "double" and 'single' quotes!'''
>>>type(t)
<class 'bytes'>
>>> t
b'This bytes object contains "double" and \'single\' quotes!'

>>> a = b'spam\xddegg'
>>> a
b'spam\xddegg'
>>> type(a)
<class 'bytes'>
>>> a[4]
221
>>> a[5]
101
>>> a[6]
103
>>> a[7]
103

>>> a = rb'spam\xddegg'
>>> a
b'spam\\xddegg'
>>> len(a)
11
>>> b = b'spam\xddegg'
>>> len(b)
8

D Parry on Aug. 2, 2020

A rookie question here:

Could you please explain in which situations bytes literal objects are used? There is some sort of logic and explanation when it comes to tuples, lists, dictionaries and strings but I could not find the answer for Bytes. (the purpose, the difference)

Thanks for anyone taking the time to answer it. :)

Dan Bader RP Team on Aug. 2, 2020

The bytes object is one of the core built-in types for manipulating binary data. A bytes object is an immutable sequence of single byte values. Each element in a bytes object is a small integer in the range 0 to 255.

Check out the tutorial linked under Supporting Material for more info: realpython.com/python-strings/#bytes-objects

D Parry on Aug. 2, 2020

Cheers!

Become a Member to join the conversation.