Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

What does 'b' mean before a string in Python?

In this article, we’ll delve into the world of byte strings and binary data in Python. We’ll explore what the 'b' prefix means before a string in Python and how it relates to working with binary dat …


Updated June 15, 2023

In this article, we’ll delve into the world of byte strings and binary data in Python. We’ll explore what the 'b' prefix means before a string in Python and how it relates to working with binary data.

Definition of the Concept

In Python, the 'b' prefix before a string is used to denote that the string contains binary data, rather than text. This type of string is called a “byte string” or “bytes object.” Byte strings are essentially containers for arbitrary sequences of bytes.

Step-by-Step Explanation

To understand what 'b' means in Python, let’s consider an example:

hello_bytes = b'Hello, World!'
print(hello_bytes)

When you run this code, hello_bytes will be printed as a sequence of hexadecimal digits (48 65 6c 6c 6f ,20 57 6f 72 6c 64 !). This is the binary representation of the string “Hello, World!”.

Now, let’s compare this with a regular string:

hello_str = 'Hello, World!'
print(hello_str)

The output will be the same as above (48 65 6c 6c 6f ,20 57 6f 72 6c 64 !), but with one crucial difference: in a regular string, Python assumes that the data is encoded using UTF-8. This means that any non-ASCII characters (like the comma and exclamation mark) are represented as single bytes.

Working with Byte Strings

Byte strings are useful when working with binary data, such as:

  • Reading or writing files
  • Sending network packets
  • Working with databases that store binary data

To manipulate byte strings in Python, you can use various methods and operators. For example:

# Create a byte string from a regular string
byte_str = b'Hello, World!'

# Print the length of the byte string
print(len(byte_str))

# Convert the byte string to a regular string (assuming UTF-8 encoding)
str = byte_str.decode('utf-8')
print(str)

# Modify a single byte in the byte string
byte_str[0] = 72  # 'H' has ASCII value 72
print(byte_str)

Conclusion

In this article, we explored what 'b' means before a string in Python: it denotes that the string contains binary data. We learned how to work with byte strings and how they differ from regular strings. By understanding byte strings, you’ll be able to handle binary data with confidence and write more robust Python code.

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp