没有换行符打印(print 'a',)打印一个空格,如何删除? [英] Printing without newline (print 'a',) prints a space, how to remove?
问题描述
我有这个代码:
<预><代码>>>>对于 xrange(20) 中的 i:...打印'a',...aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa我想输出 'a'
,没有 ' '
像这样:
aaaaaaaaaaaaaaaaaaa
有可能吗?
有多种方法可以实现您的结果.如果您只是想要一个解决方案,请使用 字符串乘法 作为 @Ant 提及.只有当您的每个 print
语句打印相同的字符串时,这才会起作用.请注意,它适用于任何长度字符串的乘法(例如 'foo' * 20
有效).
如果你想这样做一般,建立一个字符串,然后打印一次.这会为字符串消耗一点内存,但只会对 print
进行一次调用.请注意,使用 +=
的字符串连接现在与您要连接的字符串的大小成线性关系,因此速度会很快.
或者您可以更直接地使用 sys.stdout.write(),其中 print
是一个包装.这将只写入您提供的原始字符串,没有任何格式.请注意,即使在 20 个 a
的末尾也不会打印换行符.
Python 3 将 print
语句更改为 print()函数,它允许您设置一个end
参数.您可以通过从 __future__
导入来在 >=2.6 中使用它.不过,我会在任何严肃的 2.x 代码中避免这种情况,因为对于那些从未使用过 3.x 的人来说,这会有点混乱.但是,它应该能让您体验 3.x 带来的一些好处.
I have this code:
>>> for i in xrange(20):
... print 'a',
...
a a a a a a a a a a a a a a a a a a a a
I want to output 'a'
, without ' '
like this:
aaaaaaaaaaaaaaaaaaaa
Is it possible?
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print
statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20
works).
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print
. Note that string concatenation using +=
is now linear in the size of the string you're concatenating so this will be fast.
>>> for i in xrange(20):
... s += 'a'
...
>>> print s
aaaaaaaaaaaaaaaaaaaa
Or you can do it more directly using sys.stdout.write(), which print
is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 a
s.
>>> import sys
>>> for i in xrange(20):
... sys.stdout.write('a')
...
aaaaaaaaaaaaaaaaaaaa>>>
Python 3 changes the print
statement into a print() function, which allows you to set an end
parameter. You can use it in >=2.6 by importing from __future__
. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.
>>> from __future__ import print_function
>>> for i in xrange(20):
... print('a', end='')
...
aaaaaaaaaaaaaaaaaaaa>>>
这篇关于没有换行符打印(print 'a',)打印一个空格,如何删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!