HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

What does the 'b' character do in front of a string literal?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
thedoesfrontwhatliteralstringcharacter

Problem

Apparently, the following is the valid syntax:

b'The string'


I would like to know:

  • What does this b character in front of the string mean?



  • What are the effects of using it?



  • What are appropriate situations to use it?



I found a related question right here on SO, but that question is about PHP though, and it states the b is used to indicate the string is binary, as opposed to Unicode, which was needed for code to be compatible from version of PHP < 6, when migrating to PHP 6. I don't think this applies to Python.

I did find this documentation on the Python site about using a u character in the same syntax to specify a string as Unicode. Unfortunately, it doesn't mention the b character anywhere in that document.

Also, just out of curiosity, are there more symbols than the b and u that do other things?

Solution

To quote the Python 2.x documentation:


A prefix of 'b' or 'B' is ignored in
Python 2; it indicates that the
literal should become a bytes literal
in Python 3 (e.g. when code is
automatically converted with 2to3). A
'u' or 'b' prefix may be followed by
an 'r' prefix.

The Python 3 documentation states:


Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

Context

Stack Overflow Q#6269765, score: 547

Revisions (0)

No revisions yet.