如何防止Python打印添加换行符或空格?

时间:2008-10-31 22:33:22

标签: python printing formatting python-2.x

在python中,如果我说

print 'h'

我收到了字母h和换行符。如果我说

print 'h',

我收到了字母h而没有换行符。如果我说

print 'h',
print 'm',

我收到了字母h,空格和字母m。如何阻止Python打印空间?

print语句是同一循环的不同迭代,所以我不能只使用+运算符。

16 个答案:

答案 0 :(得分:268)

只是评论。在Python 3中,您将使用

print('h', end='')

禁止结束行终止符,

print('a', 'b', 'c', sep='')

来抑制项之间的空白分隔符。

答案 1 :(得分:191)

您可以使用:

sys.stdout.write('h')
sys.stdout.write('m')

答案 2 :(得分:43)

Greg是对的 - 您可以使用sys.stdout.write

但是,也许您应该考虑重构算法以累积< whatevers>的列表。然后

lst = ['h', 'm']
print  "".join(lst)

答案 3 :(得分:27)

或使用+,即:

>>> print 'me'+'no'+'likee'+'spacees'+'pls'
menolikeespaceespls

确保所有内容都是可连接的对象。

答案 4 :(得分:20)

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

答案 5 :(得分:16)

为了完整性,另一种方法是在执行写入后清除softspace值。

import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"

打印helloworld !

对于大多数情况,使用stdout.write()可能更方便。

答案 6 :(得分:13)

这可能看起来很愚蠢,但似乎是最简单的:

    print 'h',
    print '\bm'

答案 7 :(得分:9)

重新获得对控制台的控制权!简单地:

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
>>>

额外奖励:如果你不喜欢print >> f, ...,你可以将这个caper扩展到fprintf(f,...)。

答案 8 :(得分:8)

我没有添加新答案。我只是以更好的格式提出最好的答案。 我可以看到评分的最佳答案是使用sys.stdout.write(someString)。你可以尝试一下:

    import sys
    Print = sys.stdout.write
    Print("Hello")
    Print("World")

将产生:

HelloWorld

就是这样。

答案 9 :(得分:5)

在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,您可以明确设置打印功能的 sep end 参数。

答案 10 :(得分:2)

您可以像使用C中的printf函数一样使用print。

e.g。

打印“%s%s”%(x,y)

答案 11 :(得分:1)

print("{0}{1}{2}".format(a, b, c))

答案 12 :(得分:1)

sys.stdout.write是(在Python 2中)唯一可靠的解决方案。 Python 2打印很疯狂。请考虑以下代码:

print "a",
print "b",

这将打印a b,导致您怀疑它正在打印尾随空格。但这不正确。试试这个:

print "a",
sys.stdout.write("0")
print "b",

这将打印a0b。你怎么解释的? 哪里有空格?

我仍然无法弄清楚这里到底发生了什么。有人可以看看我最好的猜测:

当您, 上有print后跟时,我尝试推断出规则:

首先,让我们假设print ,(在Python 2中)不打印任何空格(空格换行符)。

但是,Python 2会注意您的打印方式 - 您使用的是print,还是sys.stdout.write还是其他什么?如果对print进行两次连续调用,那么Python将坚持在两者之间放置一个空格。

答案 13 :(得分:0)

import sys
a=raw_input()
for i in range(0,len(a)):
       sys.stdout.write(a[i])

答案 14 :(得分:0)

print('''first line \
second line''')

它会产生

  

第一行第二行

答案 15 :(得分:-3)

一旦我想从文件中读取一些数字,我就遇到了同样的问题。我这样解决了:

f = open('file.txt', 'r')
for line in f:   
    print(str.split(line)[0])
相关问题