在同一行打印新输出 [英] Print new output on same line

查看:57
本文介绍了在同一行打印新输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将循环输出打印到屏幕的同一行.

我如何以最简单的方式实现 Python 3.x

我知道 Python 2.7 已通过在行尾使用逗号(即打印 I)来询问此问题,但我找不到 Python 3.x 的解决方案.

i = 0当 i <10 时:我 += 1## 打印 (i) # python 2.7 将打印 i,print (i) # python 2.7 将是 'print i,'

屏幕输出.

12345678910

<小时>

我要打印的是:

12345678910

新读者也可以访问此链接 http://docs.python.org/release/3.0.1/whatsnew/3.0.html

解决方案

来自 help(print):

关于在模块内建函数中打印内建函数的帮助:打印(...)打印(值,...,sep='',end='\n',文件=sys.stdout)默认情况下将值打印到流或 sys.stdout.可选的关键字参数:文件:类似文件的对象(流);默认为当前的 sys.stdout.sep:值之间插入的字符串,默认为空格.end:字符串追加在最后一个值之后,默认换行.

您可以使用 end 关键字:

<预><代码>>>>对于范围内的 i (1, 11):...打印(我,结束='')...12345678910>>>

请注意,您必须自己print() 最后的换行符.顺便说一句,在 Python 2 中你不会得到带有尾随逗号的12345678910",你会得到 1 2 3 4 5 6 7 8 9 10 .

I want to print the looped output to the screen on the same line.

How do I this in the simplest way for Python 3.x

I know this question has been asked for Python 2.7 by using a comma at the end of the line i.e. print I, but I can't find a solution for Python 3.x.

i = 0 
while i <10:
     i += 1 
     ## print (i) # python 2.7 would be print i,
     print (i) # python 2.7 would be 'print i,'

Screen output.

1
2
3
4
5
6
7
8
9
10


What I want to print is:

12345678910

New readers visit this link aswell http://docs.python.org/release/3.0.1/whatsnew/3.0.html

解决方案

From help(print):

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

You can use the end keyword:

>>> for i in range(1, 11):
...     print(i, end='')
... 
12345678910>>> 

Note that you'll have to print() the final newline yourself. BTW, you won't get "12345678910" in Python 2 with the trailing comma, you'll get 1 2 3 4 5 6 7 8 9 10 instead.

这篇关于在同一行打印新输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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