这个问题已经有一个答案在这里:

在python,如果我说

print 'h'

我得到的字母h和a newline.如果我说

print 'h',

我得到的字母h和没有换行。如果我说

print 'h',
print 'm',

我得到的信h、空格和字母m.我怎么可以阻止蟒蛇从印刷空间?

打印的发言是不同的迭代的同样的循环,所以我不能使用操作员。

有帮助吗?

解决方案

你可以使用:

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

其他提示

只是一个意见。在 蟒蛇3, 你会用

print('h', end='')

来抑制的底线的终结者,

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

来抑制空白隔板之间的项目。

格雷格是正确的-你可以使用sys.stdout。写

不过,或许你应该考虑重构算法中积累的列表 <whatevers> 然后

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

或者使用 +, ,即:

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

只需确保所有人都将能够对象。

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 直接。

为了完整性,另一种方式是明确的softspace值之后进行编写。

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

印刷品 helloworld !

使用stdout。write()可能是更便于大多数情况下,虽然。

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

    print 'h',
    print '\bm'

重新控制你的控制台!简单地说:

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, ..., 你可以延伸这个案子来函数(f,...).

我不添加一个新的答案。我只是把最好的标记在回答一个更好的格式。我可以看到,最好的答案通过评价是使用 sys.stdout.write(someString).你可以试试这个出:

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

将产率:

HelloWorld

这是所有。

在python2.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
>>>

因此,使用print_function从__未来__你可以设定明确的 sep结束 parameteres的打印功能。

你可以使用打印喜欢的printf功能C。

例如

印"%s%s"%(x,y)

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

sys.stdout.write 是(在蟒蛇2)仅可靠的解决方案。蟒蛇2印刷是疯狂的。考虑这个代号:

print "a",
print "b",

这将打印 a b, ,导致你到怀疑,它是打印一个后空间。但这不是正确的。试试这个代替:

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

这将打印 a0b.你怎么解释? 其中有的空间去了?

我仍然相当不能做出来什么是真的在这里。可能有人看过我最好的猜测:

我尝试推断规则的时候你有一个结尾 , 在您的 print:

第一,让我们假设 print , (Python2)并不打印的任何空白(空间 也不 新行).

蟒蛇2但是注意到你是如何印刷-你使用 print, 或 sys.stdout.write, 或其他什么东西?如果你做两个 连续的 呼叫 print, 然后蟒蛇会坚持把空间之间的两个。

import sys
a=raw_input()
for i in range(0,len(a)):
       sys.stdout.write(a[i])
print('''first line \
second line''')

它将产生

第一行第二线

我有同样的问题一旦我想读一些数字从一个文件。我解决了这样的:

f = open('file.txt', 'r')
for line in f:   
    print(str.split(line)[0])
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top