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