在python中使用未定义的变量

aqu*_*lin 0 python variables

此代码正确标记错误:

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

.

NameError: name 'b' is not defined
Run Code Online (Sandbox Code Playgroud)

但是使用这个代码,在标签之前忘记逗号的地方,不会这样做:

print "Value b and tab: ", b"\t-"
b=1
print "Value b and tab: ", b"\t-"
Run Code Online (Sandbox Code Playgroud)

什么是python思考,什么时候看到b"\t-"?为什么即使它被分配,它也不会打印出b的值?

Mar*_*ers 7

b'...'是Python 3中的字节字符串文字.

在Python 2中,它是常规字符串的别名,用于向前兼容Python 3.请参阅Python 2.6 什么是新文档,特别是PEP 3112:字节文字部分:

Python 3.0采用Unicode作为语言的基本字符串类型,并且以不同的方式表示8位字面值,b'string'或者使用字节构造函数.为了将来的兼容性,Python 2.6添加bytes了该str类型的同义词,并且它还支持该b''表示法.

和Python参考文档的词法分析章节中的字符串文字部分:

Python 2中的前缀'b'或被'B'忽略; 它表示文字应该成为Python 3中的字节文字(例如,当代码自动转换为2to3时).

因为在Python 2中,语法创建了一个常规的Python字符串,然后回显该值,显示正常的字符串语法,没有b前缀.