DEV Community


Posted on

What does the 'b' character do in front of a string literal in Python?

Python sometimes has the 'b' character in front of a string. You are going to learn how to make a variable type as byte.

You will also learn what the 'b' character does in Python


Consider the following examples,

    # variable definitions
    t_str = 'string'
    t_bytes = b'string'

    # print the types

You can try this both in the shell and from a script

The program above outputs this:

<class 'str'>
<class 'bytes'>

This means they are of a different type.

data types

String vs bytes

As per the above example, the prefix of 'b' character to a string, makes the variable of data type bytes.

In the prefix 'b' before version 3, python ignored the variable bytes with 'b' in the later version. It can contain ASCII characters and it should be expressed bytes with an escape value of 128 or higher.

The bytes are the actual data. Strings are an abstraction. A byte is a collection of 8 bits, also known as binary

Read more:

Top comments (0)