×

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

By Sapna Deraje Radhakrishna Last updated : December 15, 2024

Python - 'b' character in string literals

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 this difference is essential for handling text and binary data effectively in Python.

Example

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

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.

Comments and Discussions!

Load comments ↻





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