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
' ' like this:
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
'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
+= 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
>>> import sys >>> for i in xrange(20): ... sys.stdout.write('a') ... aaaaaaaaaaaaaaaaaaaa>>>
Python 3 changes the
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>>>
>>> from __future__ import print_function >>> print('a', end='')
Obviously that only works with python 3.0 or higher (or 2.6+ with a
from __future__ import print_function at the beginning). The
print() function by default in Python 3.0.