Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the right-shift operator work in a python print statement?

Tags:

python

grammar

I've seen someone using "print" with ">>" to write stuffs into a file:

In [7]: with open('text', 'w') as f:
   ...:     print >> f, "Hello, world!"
   ...:

In [8]: !type text
Hello, world!

How does it work? When should I use this instead of just using the "write" method?

like image 599
Wang Dingwei Avatar asked Jun 20 '10 02:06

Wang Dingwei


People also ask

How does right shift work in Python?

Bitwise Right Shift Operator Python right shift operator is exactly the opposite of the left shift operator. Then left side operand bits are moved towards the right side for the given number of times. In simple terms, the right side bits are removed.

How does a right shift operator work?

The right shift operator ( >> ) returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a two's complement bit string) to the right by the number of bits, modulo 32, specified in the second operand.

What is >> and << in Python?

They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.


1 Answers

From https://docs.python.org/2/reference/simple_stmts.html#the-print-statement

print also has an extended form, defined by the second portion of the syntax described above. This form is sometimes referred to as “print chevron.” In this form, the first expression after the >> must evaluate to a “file-like” object, specifically an object that has a write() method as described above. With this extended form, the subsequent expressions are printed to this file object. If the first expression evaluates to None, then sys.stdout is used as the file for output.

like image 169
Ed. Avatar answered Oct 16 '22 17:10

Ed.