做什么 >>并且<<在 Python 中是什么意思? [英] What do >> and << mean in Python?

查看:38
本文介绍了做什么 >>并且<<在 Python 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到我可以做诸如 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

这篇关于做什么 &gt;&gt;并且&lt;&lt;在 Python 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆