What is ‘b’ in front of string and how to remove that in Python?

If you are familiar with Python, you may be well aware of the different Python data types including strings and bytes.
While programming, you may have come across strings with “b” as a prefix. What exactly is this b in front of the string? What does it indicate and why is it used? Further, how do you remove the same?

Well, let us find answers to all these questions by reading further into this tutorial.

What is ‘b’ in front of string?

The ‘b’ notations before a string are used to declare the particular string as a byte string. A byte string is nothing but an array of bytes consisting of integers between 0 and 255. On the other hand, a character string is simply a sequence of characters.

In Python version 2 and below, the b prefix is usually ignored. However, in version 3, the same instantiates/specifies a byte object instead of a regular string object.

You can understand the same by looking into the below demonstration:

string1 = 'CodeSpeedy' 
print(type(string1))  
string2 = b'CodeSpeedyl' 
print(type(string2))
<class 'str'>
<class 'bytes'>

Thus, though both the strings appear to be the same, their data types are different.

Here is another demonstration in which we feed a character string as input and then convert it to a byte string.

string = 'This is a string'
print(string.encode())
b'This is a string'

Thus, the string converted to byte string is preceded by ‘b’ as shown.

How to remove b’ from the prefix of a string in Python

Using the decode() method: Converting byte string back to a character string

string1 = b'CodeSpeedy'
print(string1)
print(type(string1))
string1_aft_decode = string1.decode()
print(string1_aft_decode)
print(type(string1_aft_decode))
b'CodeSpeedy'
<class 'bytes'>
CodeSpeedy
<class 'str'>

Using the codecs module: Converting byte string back to a character string

import codecs
string1 = b'CodeSpeedy'
print(string1)
print(type(string1))
string1_aft_decode = codecs.decode(string1)
print(string1_aft_decode)
print(type(string1_aft_decode))
b'CodeSpeedy'
<class 'bytes'>
CodeSpeedy
<class 'str'>

Thus on being converted to a normal string, the ‘b’ in the prefix is automatically gone.

Also read, Encoding and Decoding Base64 Strings in Python

A related topic you can check out How to use Python Raw Strings

Leave a Reply

Your email address will not be published.