python中的不换行输出
2015-11-13
在Python中实现换行,我本来以为只是一件小事情,结果发现没那么简单。
Python 2.X
- print后加上
,
for i in range(100): if i%10==0 and i!=0: print "\n" print i,
注意,虽然没有换行,但是在两次输出之间还是默认有一定的距离。
- 使用
sys.stdout.write()
。当然你得先引入sys这个库,而且有时候需要在这个后面加上sys.stdio.flush()
,不然可能因为在缓存区里看不见。
import sys
for i in range(100):
if i%10==0:
print "\n"
sys.stdout.write(str(i)+" ")
注意,打印的参数只能是字符串或者是数组。
Python 3.X
- print()的原型是
print(*objects,sep='',end='\n',file=sys.stdout,flush=False)
,所以只需要将end='\n'
给替换掉就可以了。
for i in range(100):
if i%10==0:
print("")
print(i,end=" ")
- 也是使用
sys.stdout.write
import sys
for i in range(100):
if i%10==0 and i!=0:
print("")
sys.stdout.write(str(i)+" ")
本文固定链接:https://windard.com/project/2015/11/13/No-Line-Break-In-Python
原创文章,转载请注明出处:python中的不换行输出 By Windard