What do >> and << mean in Python?

后端 未结 7 1819
无人共我
无人共我 2020-12-04 09:44

I notice that I can do things like 2 << 5 to get 64 and 1000 >> 2 to get 250.

Also I can use >> in pri

7条回答
  •  粉色の甜心
    2020-12-04 09:52

    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, 
    

    example

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

    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
    

提交回复
热议问题