简体   繁体   English

在python 2和3中的第一行打印在同一行

[英]Print on same line at the first in python 2 and 3

There are several solutions for printing on same line and at the first of it, like below. 有几种解决方案可以在同一行和第一行打印,如下所示。

In python 2, 在python 2中,

print "\r Running... xxx",

And in Python 3, 在Python 3中,

print("\r Running... xxx", end="")

I can't find a single print solution to cover python 2 and 3 at the same time. 我无法找到同时覆盖python 2和3的单一打印解决方案。 Do I have to use sys.stdout.write ? 我必须使用sys.stdout.write吗?

Use from __future__ import print_function and use the print() function in both Python 2 and Python 3: 使用from __future__ import print_function并在Python 2和Python 3中使用print()函数:

from __future__ import print_function

print("\r Running... xxx", end="")  # works across both major versions

See the print() function documentation in Python 2 : 请参阅Python 2中print()函数文档

Note : This function is not normally available as a built-in since the name print is recognized as the print statement. 注意 :此功能通常不作为内置函数提供,因为名称print被识别为print语句。 To disable the statement and use the print() function, use this future statement at the top of your module: 要禁用该语句并使用print()函数,请在模块顶部使用此future语句:

 from __future__ import print_function 

The print() function was added to Python 2.6. print()函数已添加到Python 2.6中。

Use 采用

from __future__ import print_function

in Python 2 and use print as a function in Python 2 also 在Python 2中也使用print作为Python 2中的函数

print("\r Running... xxx", end="")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM