考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
考虑在Python中使用print的以下示例:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
在每个值之间添加换行符或空格。我怎样才能避免这种情况,从而使输出。。。。相反换句话说,如何将字符串“附加”到标准输出流?
当前回答
或具有如下功能:
def Print(s):
return sys.stdout.write(str(s))
现在:
for i in range(10): # Or `xrange` for the Python 2 version
Print(i)
输出:
0123456789
其他回答
您可以在Python 3中执行以下操作:
#!usr/bin/python
i = 0
while i<10 :
print('.', end='')
i = i+1
并使用python filename.py或python3 filename.py。
您不需要导入任何库。只需使用删除字符:
BS = u'\0008' # The Unicode point for the "delete" character
for i in range(10):print(BS + "."),
这将删除换行符和空格(^_^)*。
Python 3.x中的print函数有一个可选的结束参数,可用于修改结束字符:
print("HELLO", end="")
print("HELLO")
输出:
你好,你好
分隔符也有sep:
print("HELLO", "HELLO", "HELLO", sep="")
输出:
你好你好
如果您想在Python2.x中使用它,只需在文件开头添加:
from __future__ import print_function
注意:这个问题的标题以前类似于“How to printf in Python”
由于人们可能会根据标题来这里寻找它,Python也支持printf样式替换:
>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
... print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three
而且,您可以方便地相乘字符串值:
>>> print "." * 10
..........
Python 3:
print('.', end='')
Python 2.6+:
from __future__ import print_function # needs to be first statement in file
print('.', end='')
Python<=2.5:
import sys
sys.stdout.write('.')
如果每次打印后都有多余的空间,在Python 2中:
print '.',
Python 2中的误导-避免:
print('.'), # Avoid this if you want to remain sane
# This makes it look like print is a function, but it is not.
# This is the `,` creating a tuple and the parentheses enclose an expression.
# To see the problem, try:
print('.', 'x'), # This will print `('.', 'x') `