1

This code properly flags an error:

print "Value b and tab: ", b,"\t-"
b=1
print "Value b and tab: ", b,"\t-"

.

NameError: name 'b' is not defined

But using this code, where the comma was forgotten before the tab, does not do the same:

print "Value b and tab: ", b"\t-"
b=1
print "Value b and tab: ", b"\t-"

What is python thinking, when it sees b"\t-"? And why doesn't it print out the value of b even when it is assigned?

2 Answers 2

8

b'...' is a byte string literal in Python 3.

In Python 2 that is an alias for a regular string, for forwards compatibility with Python 3. See the Python 2.6 What's New document, specifically the PEP 3112: Byte Literals section:

Python 3.0 adopts Unicode as the language’s fundamental string type and denotes 8-bit literals differently, either as b'string' or using a bytes constructor. For future compatibility, Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' notation.

and the String literals section in the lexical analysis chapter of the Python reference 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).

Because in Python 2 the syntax creates a regular Python string, echoing the value afterwards shows the normal string syntax, without the b prefix.

Sign up to request clarification or add additional context in comments.

Comments

1

The reason this happens is because b before a string literal is interpreted as a command to interpret the string as a byte string. So b'...' is very different from a raw string literal '...'.

This is very common, and is not restricted to just 'b':

  • r'...' is interpreted as a raw string.
  • u'...' is interpreted as a Unicode string.

and so on.

Basically, try to avoid prepending characters to Python characters as they may change your data types completely.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.