python - 打印功能中的逗号结尾有什么用?

标签 python

此代码来自 http://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions

with open("myfile.txt") as f:
    for line in f:
        print line,

我不明白打印命令末尾的 , 是什么。

我还检查了文档,http://docs.python.org/2/library/functions.html#print .

理解不够,是不是搞错了?(好像不是,来自官方教程)。

我来自 ruby​​/javascript,这对我来说很不寻常。

最佳答案

在python 2.7中,逗号是为了表示字符串会打印在同一行

例如:

for i in xrange(10):
     print i,

这将打印出来

1 2 3 4 5 6 7 8 9 

要在 python 3 中执行此操作,您可以这样做:

 for i in xrange(10):
      print(i,end=" ")

你可能会发现这个答案很有帮助

Printing horizontally in python

---- 编辑 ---

文档,http://docs.python.org/2/reference/simple_stmts.html#the-print-statement , 说

A '\n' character is written at the end, unless the print statement ends with a comma.

关于python - 打印功能中的逗号结尾有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18908897/

相关文章:

python - 如何在 python 中表示方波以及如何对其进行卷积?

python - 如何使用正则表达式将缩写与其含义相匹配?

python - 使用 PIL 或 cv2 等模块在 python 中捕获屏幕的最有效方法是什么?因为它占用了很多内存

Python3 元类 : use to validate constructor argument

Python - 在当前 Windows 资源管理器中获取所选文件的路径

python - 如果类被重命名,则维护静态方法调用

python - 迁移到 Twitter API 版本 1.1(?)

python - 如何从文本中获取前 N 个句子?

python - 由 Flask sqlalchemy 模型中的关系字段创建的数据库字段

python - 如何优雅地找到 Python 枚举中的下一个和上一个值?