在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语句是同一个循环的不同迭代,所以我不能只使用+运算符。
当前回答
import sys
a=raw_input()
for i in range(0,len(a)):
sys.stdout.write(a[i])
其他回答
为了完整起见,另一种方法是在执行写入之后清除软空间值。
import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"
你好世界印刷品!
在大多数情况下,使用stdout.write()可能更方便。
print('''first line \
second line''')
它会产生
第一行,第二行
Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print "hello",; print "there"
hello there
>>> print "hello",; sys.stdout.softspace=False; print "there"
hellothere
但实际上,应该直接使用sys.stdout.write。
import sys
sys.stdout.write('h')
sys.stdout.flush()
sys.stdout.write('m')
sys.stdout.flush()
您需要调用sys.stdout.flush(),否则它将把文本保存在缓冲区中,而您将看不到它。
这看起来很愚蠢,但似乎是最简单的:
print 'h',
print '\bm'