Asked By – pythonFoo
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?
Now we will see solution for issue: Printing without newline (print ‘a’,) prints a space, how to remove?
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>>>
This question is answered By – moinudin
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0