Python 无新行输出
在没有新行结尾的情况下,如何将文本输出到控制台? 例如:Python 无新行输出,python,newline,Python,Newline,在没有新行结尾的情况下,如何将文本输出到控制台? 例如: print 'temp1' print 'temp2' 输出: temp1 temp2 我需要: temp1temp2 试试这个: print 'temp1', print 'temp2' 在最后一个参数后添加逗号: print 'temp1', print 'temp2' 或者,调用sys.stdout.write: import sys sys.stdout.write("Some output") 有多种方法,但通常的
print 'temp1'
print 'temp2'
输出:
temp1
temp2
我需要:
temp1temp2
试试这个:
print 'temp1',
print 'temp2'
在最后一个参数后添加逗号:
print 'temp1',
print 'temp2'
或者,调用sys.stdout.write
:
import sys
sys.stdout.write("Some output")
有多种方法,但通常的选择是使用
sys.stdout.write()
,它与print
不同,可以准确地打印您想要的内容。在Python3.x中(或者在Python2.6中,使用来自未来导入打印函数的)也可以使用print(s,end='',sep='')
,但此时sys.stdout.write()
可能更容易
另一种方法是构建单个字符串并打印:
>>> print "%s%s" % ('temp1', 'temp2')
但这显然需要您等待编写,直到您知道这两个字符串,这并不总是可取的,这意味着将整个字符串存储在内存中(对于大字符串,这可能是一个问题)。在Python>2.6和Python 3中:
from __future__ import print_function
print('temp1', end='')
print('temp2', end='')
试一试
逗号仍将在字符串之间引入一个空格。逗号仍将在字符串之间引入一个空格。请注意,这仍将在test1和test2之间添加一个空格,这不是OP所需要的。在第一位后添加一个.replace(“,”)。sys.stdout.write()似乎还将字符数追加到输出中。sys.stdout.write(“test”)打印test4。它为什么要这样做,我如何让它停止?虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,只使用代码的答案是没有用的。
print 'temp1',
print '\btemp2'
for i in range(4):
print(a[i], end =" ")