What does b prefix before a String mean in Python?


b prefix to string in Python
str1 = "Hello World!"
str2 = b"Hello World!"

print(type(str1))
print(type(str2))
Output:

<class 'str'>
<class 'bytes'>

If you see a String Literal in Python (3+) that has a b prefixed before it, it is an instance of the bytes type and not of str type


Note: A byte literal can contain only ASCII characters; bytes with a numeric value of 128 or greater should be denoted with an escape value.

message = b"Hållo World"
print(message)

SyntaxError: bytes can only contain ASCII literal characters.

Read More: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
-


Have Questions? Post them here!


Top Hashtags: