Effect of ‘b’ character in front of a string literal in Python
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) |
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)) |
<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) |
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)) |
<class 'str'>
Please Login to comment...