传统的 Python 打印方法经常在打印值之间插入换行符或空格,导致输出混乱。本文探讨了克服这个问题并实现连续输出的方法。
在 Python 3 中,print 函数提供了 sep= 和 end= 参数来自定义打印字符串:
要抑制换行符,请使用 end='':
print('.', end='')
删除空格在参数之间,设置 sep='':
print('a', 'b', 'c', sep='')
对于高级控制,包括flush=True 参数:
print('.', end='', flush=True)
在 Python 2.6 和 2.7 中,还有替代方法:
导入 Python 3 的 print函数:
from __future__ import print_function
使用 sys.stdout.write():
import sys sys.stdout.write('.')
后跟:
sys.stdout.flush()
以上是如何在 Python 中打印而不使用换行符或空格?的详细内容。更多信息请关注PHP中文网其他相关文章!