右移运算符如何在python打印语句中工作? [英] How does the right-shift operator work in a python print statement?

查看:75
本文介绍了右移运算符如何在python打印语句中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过有人使用带有">>"的打印"来将内容写入文件:

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?

推荐答案

来自

print也有扩展形式, 由第二部分定义 上述语法.这个表格是 有时也称为印刷品" 人字形."以这种形式,第一个 >>之后的表达式必须求值 到类似文件"的对象,特别是 具有write()方法的对象 如上所述.有了这个扩展 形式,随后的表达式是 打印到此文件对象.如果 第一个表达式的计算结果为无, 然后将sys.stdout用作文件 输出.

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.

这篇关于右移运算符如何在python打印语句中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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