我注意到我可以用2 << 5来得到64,用1000 >> 2来得到250。

我也可以在打印中使用>>:

print >>obj, "Hello world"

这里发生了什么?


当前回答

<< Mean any given number will be multiply by 2the power
for exp:- 2<<2=2*2'1=4
          6<<2'4=6*2*2*2*2*2=64

其他回答

<< Mean any given number will be multiply by 2the power
for exp:- 2<<2=2*2'1=4
          6<<2'4=6*2*2*2*2*2=64

这些是位移位运算符。

从文件中引用:

x << y

返回x,其中的位向左移动了y位(右边的新位为零)。这就等于x乘以2**y。

x >> y

返回x,位向右移动y位。这和x除以2**y是一样的。

另一种情况涉及print >>obj, "Hello World"是Python 2中print语句的"print chevron"语法(在Python 3中被删除,由print()函数的file参数取代)。输出不是写入标准输出,而是传递给obj.write()方法。一个典型的例子是具有write()方法的文件对象。请参阅最近一个问题的答案:Python中的双大于号。

这些是移位运算符

x << y返回x,其中比特向左移动y位(和 右边的新位是零)。这和 x乘以2**y。 x >> y返回x,位移位到 右移y位。这和//'ing x * 2* y是一样的。

在您的示例中,>>操作符用于两个不同的目的。在c++术语中,这个操作符是重载的。在第一个例子中,它被用作位运算符(右移),

2 << 5  # shift left by 5 bits
        # 0b10 -> 0b1000000
1000 >> 2  # shift right by 2 bits
           # 0b1111101000 -> 0b11111010

而在第二个场景中,它用于输出重定向。你可以用它来处理文件对象,就像下面这个例子:

with open('foo.txt', 'w') as f:
    print >>f, 'Hello world'  # "Hello world" now saved in foo.txt

>>的第二次使用只适用于Python 2。在Python 3中,可以使用file=参数重定向print()的输出:

with open('foo.txt', 'w') as f:
    print('Hello world', file=f)  # "Hello world" now saved in foo.txt