Open In App

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

Last Updated : 30 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, the ‘b’ character before a string is used to specify the string as a “byte string”.By adding the ‘b’ character before a string literal, it becomes a bytes literal. This means that the string content should be interpreted as a sequence of bytes rather than characters. Example:

[GFGTABS]
Python

bs = b'GeeksforGeeks'
print(type(bs))


[/GFGTABS]

Output

<class 'bytes'>

Explanation: Notice that the datatype of bs is bytes because of the prefix b.

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.

[GFGTABS]
Python

s = "GeeksForGeeks"
print("String:", s)
print("Type:", type(s))

bs = b"GeeksForGeeks"
print("Byte String:", bs)
print("Type:", type(bs))


[/GFGTABS]

Output

String: GeeksForGeeks
Type: <class 'str'>
Byte String: b'GeeksForGeeks'
Type: <class 'bytes'>

Explanation:

  • Byte strings are shown with a b prefix and surrounded by single or double quotes.
  • Strings are Unicode by default and are human-readable.

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.

[GFGTABS]
Python

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


[/GFGTABS]

Output

b'Hey I am a String'

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

[GFGTABS]
Python

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


[/GFGTABS]

Output

<class 'bytes'>

How to Convert Bytes Back to String

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

[GFGTABS]
Python

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


[/GFGTABS]

Output

Hey I am a Byte String

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

[GFGTABS]
Python

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


[/GFGTABS]

Output

<class 'str'>

Related articles:



Next Article
Article Tags :
Practice Tags :

Similar Reads