What does b prefix before a String mean in Python?

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


<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"

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) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. 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 2023 | Privacy Policy | About Us | Contact Us | Sitemap