Effect of 'b' character in front of a string literal in Python
Last Updated :
30 Apr, 2025
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:
Python
bs = b'GeeksforGeeks'
print(type(bs))
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.
Python
s = "GeeksForGeeks"
print("String:", s)
print("Type:", type(s))
bs = b"GeeksForGeeks"
print("Byte String:", bs)
print("Type:", type(bs))
OutputString: 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.
Python
var = 'Hey I am a String'.encode('ASCII')
print(var)
Outputb'Hey I am a String'
If we even print the type of the variable, we will get the byte type:
Python
var = 'Hey I am a String'.encode('ASCII')
print(type(var))
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:
Python
var = b'Hey I am a Byte String'.decode('ASCII')
print(var)
OutputHey I am a Byte String
If we even print the type of variable, we will get the string type:
Python
var = b'Hey I am a String'.decode('ASCII')
print(type(var))
Related articles: