问题描述
我注意到我可以做诸如 2 << 之类的事情.5
得到 64 和 1000 >>2
得到 250.
I notice that I can do things like 2 << 5
to get 64 and 1000 >> 2
to get 250.
我也可以在print
中使用>>
:
print >>obj, "Hello world"
这里发生了什么?
推荐答案
我认为这是一个重要的问题,但尚未得到解答(OP 似乎已经了解移位运算符).让我试着回答一下,您示例中的 >> 运算符用于两个不同的目的.在 C++ 术语中,此运算符是重载的.在第一个示例中,它用作按位运算符(左移),而在第二个场景中,它仅用作输出重定向.即
I think it is important question and it is not answered yet (the OP seems to already know about shift operators). Let me try to answer, the >> operator in your example is used for two different purposes. In c++ terms this operator is overloaded. In the first example it is used as bitwise operator (left shift), while in the second scenario it is merely used as output redirection. i.e.
2 << 5 # shift to left by 5 bits
2 >> 5 # shift to right by 5 bits
print >> obj, "Hello world" # redirect the output to obj,
示例
with open('foo.txt', 'w') as obj:
print >> obj, "Hello world" # hello world now saved in foo.txt
更新:
在 python 3 中,可以直接给出文件参数,如下所示:
update:
In python 3 it is possible to give the file argument directly as follows:
print("Hello world", file=open("foo.txt", "a")) # hello world now saved in foo.txt
这篇关于做什么 >>并且<<在 Python 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!