Skip to content
Related Articles

Related Articles

Effect of ‘b’ character in front of a string literal in Python

View Discussion
Improve Article
Save Article
  • Last Updated : 15 Jun, 2022
View Discussion
Improve Article
Save Article

In python, the ‘b‘ character before a string is used to specify the string as a “byte string“. 

For example:

b_str = b’Hey I am a byte String’

Now, b_str doesn’t store a String object, instead, it stores a Byte String object.

Difference between Strings and Byte Strings:

Strings are normal characters that are in human-readable format whereas Byte strings are strings that are in bytes. Generally, strings are converted to bytes first just like any other object because a computer can store data only in bytes. When working with byte strings, they are not converted into bytes as they are already in bytes.

How are strings converted to bytes?

Strings are converted to bytes, using encoding. There are various encoding formats through which strings can be converted to bytes. For eg. ASCII, UTF-8, etc…

To convert a string to byte string in python:

Python3




var = 'Hey I am a String'.encode('ASCII')
print(var)

Output

b'Hey I am a String'

If we even print the type of the variable, we will get the byte type:

Python3




var = 'Hey I am a String'.encode('ASCII')
print(type(var))

Output

<class 'bytes'>

How is a byte object converted to a String?

Just like encoding is used to convert a string to a byte, we use decoding to convert a byte to a string:

Python3




var = b'Hey I am a Byte String'.decode('ASCII')
print(var)

Output

Hey I am a Byte String

If we even print the type of variable, we will get the string type:

Python3




var = b'Hey I am a String'.decode('ASCII')
print(type(var))

Output

<class 'str'>

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!