在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语句是同一个循环的不同迭代,所以我不能只使用+运算符。
当前回答
你可以像使用C语言中的printf函数一样使用print。
e.g.
打印“%s%s”% (x, y)
其他回答
print('''first line \
second line''')
它会产生
第一行,第二行
或者使用+,即:
>>> print 'me'+'no'+'likee'+'spacees'+'pls'
menolikeespaceespls
只要确保所有对象都是可连接的对象。
这看起来很愚蠢,但似乎是最简单的:
print 'h',
print '\bm'
在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参数。
Greg是对的——您可以使用sys.stdout.write
但是,也许您应该考虑重构您的算法,以积累一个<whatever >的列表,然后
lst = ['h', 'm']
print "".join(lst)