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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap