×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Effect of 'b' character in front of a string literal in Python

Last Updated : April 27, 2025

In Python, strings and bytes are distinct data types that serve different purposes. Strings (str) represent text data and are sequences of Unicode characters, while bytes (bytes) represent raw binary data and are sequences of byte values. The distinction becomes clear with the use of a b prefix, which denotes a bytes literal, transforming the data type from str to bytes.

Understanding the 'b' Prefix in String Literals

The b prefix is used to specify a bytes literal in Python. When the b is placed before a string, it indicates that the string should be treated as raw binary data, not as text.

Example: Comparing Strings and Bytes

Consider the following examples,

# variable declarations
test_str = 'string'
test_bytes = b'string'

# printing the types
print(type(test_str))
print(type(test_bytes))

Output

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

Explanation of the 'b' Prefix

As per the above example, the prefix of 'b' character to a string, makes the variable of type bytes.

Before version 3, python always ignored the prefix 'b' and in the later version, bytes variable are always prefixed with ‘b’. They may contain ASCII characters, bytes with a numeric value of 128 or greater must be expressed with escapes.

The bytes are the actual data. Strings are an abstraction.

Python 'b' Character with String Literals Exercise

Select the correct option to complete each statement about the 'b' character with string literals in Python.

  1. The 'b' prefix before a string literal in Python denotes a ___ string, which stores data as bytes.
  2. When using the 'b' prefix, Python does not support the use of ___ characters in the string.
  3. In Python 3.x, a 'b' string is treated as a sequence of ___ instead of characters.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.