在python中,如果我说
print 'h'
得到字母h和换行符。如果我说
print 'h',
我得到了字母h,没有换行符。如果我说
print 'h',
print 'm',
我得到字母h,一个空格,和字母m。我如何阻止Python打印空格?
print语句是同一个循环的不同迭代,所以我不能只使用+运算符。
在python中,如果我说
print 'h'
得到字母h和换行符。如果我说
print 'h',
我得到了字母h,没有换行符。如果我说
print 'h',
print 'm',
我得到字母h,一个空格,和字母m。我如何阻止Python打印空格?
print语句是同一个循环的不同迭代,所以我不能只使用+运算符。
当前回答
在python 2.6中:
>>> print 'h','m','h'
h m h
>>> from __future__ import print_function
>>> print('h',end='')
h>>> print('h',end='');print('m',end='');print('h',end='')
hmh>>>
>>> print('h','m','h',sep='');
hmh
>>>
因此,使用__future__中的print_function,你可以显式地设置print函数的sep和end参数。
其他回答
在Python 3中,使用
print('h', end='')
来抑制结束线终止符,和
print('a', 'b', 'c', sep='')
禁用项之间的空格分隔符。请参阅打印文档
Greg是对的——您可以使用sys.stdout.write
但是,也许您应该考虑重构您的算法,以积累一个<whatever >的列表,然后
lst = ['h', 'm']
print "".join(lst)
在python 2.6中:
>>> print 'h','m','h'
h m h
>>> from __future__ import print_function
>>> print('h',end='')
h>>> print('h',end='');print('m',end='');print('h',end='')
hmh>>>
>>> print('h','m','h',sep='');
hmh
>>>
因此,使用__future__中的print_function,你可以显式地设置print函数的sep和end参数。
为了完整起见,另一种方法是在执行写入之后清除软空间值。
import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"
你好世界印刷品!
在大多数情况下,使用stdout.write()可能更方便。
重新控制你的控制台!简单:
from __past__ import printf
其中__past__.py包含:
import sys
def printf(fmt, *varargs):
sys.stdout.write(fmt % varargs)
然后:
>>> printf("Hello, world!\n")
Hello, world!
>>> printf("%d %d %d\n", 0, 1, 42)
0 1 42
>>> printf('a'); printf('b'); printf('c'); printf('\n')
abc
>>>
额外奖励:如果你不喜欢打印>> f,…,您可以将此跳跃扩展到fprintf(f,…)。