125

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?

moinudin
  • 134,091
  • 45
  • 190
  • 216
pythonFoo
  • 2,194
  • 3
  • 15
  • 17
  • 4
    I'm surprised that no-one's yet mentioned `"".join("a" for i in xrange(20))`. (It's much more flexible than just doing `"a" * 20`, as I assume it's a simplfied example). – Thomas K Dec 21 '10 at 12:59

13 Answers13

132

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

>>> 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>>> 
Alan W. Smith
  • 24,647
  • 4
  • 70
  • 96
moinudin
  • 134,091
  • 45
  • 190
  • 216
  • 4
    @A A I read the question when the string multiplication answer was present, and thought I'd give an overview of several options. The others came while I was putting together my answer. It was accepted soon after, otherwise I would've likely deleted it. – moinudin Dec 21 '10 at 12:59
  • 10
    -1 Don't build up strings by concatenation; it's O(n^2) instead of O(n). Use `"".join(...)` instead. – Katriel Dec 21 '10 at 13:02
  • 10
    I have no problem with your answer, it summarizes everything and that's good. But by doing this, you discourage other people who answer. There are many good answers and all deserve +1. Just imagine if everyone started making summaries. – user225312 Dec 21 '10 at 13:03
  • 3
    @katrielalex: Does it matter? Has the OP asked for optimization or complexity? And will it matter for 20 strings? Come on, you seriously must be joking. – user225312 Dec 21 '10 at 13:04
  • 1
    @katrielalex Wrong, string concatenation using `+=` in Python is a constant time operation for concatenation of a single character. – moinudin Dec 21 '10 at 13:06
  • 1
    I've started a discussion about this on [meta](http://meta.stackexchange.com/questions/72893/acceptable-to-group-together-many-answers-into-a-new-one-explaining-when-each-is) – moinudin Dec 21 '10 at 13:17
119

From PEP 3105: print As a Function in the What’s New in Python 2.6 document:

>>> 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 statement was removed and became the print() function by default in Python 3.0.

martineau
  • 119,623
  • 25
  • 170
  • 301
Antoine Pelisse
  • 12,871
  • 4
  • 34
  • 34
41

You can suppress the space by printing an empty string to stdout between the print statements.

>>> import sys
>>> for i in range(20):
...   print 'a',
...   sys.stdout.write('')
... 
aaaaaaaaaaaaaaaaaaaa

However, a cleaner solution is to first build the entire string you'd like to print and then output it with a single print statement.

Pär Wieslander
  • 28,374
  • 7
  • 55
  • 54
  • 4
    @Soulseekah: Yes, using only `sys.stdout.write()` is more convenient in this case. However, I wanted to show that writing an empty string to stdout suppresses the space between elements written using `print`, which could be useful in similar situations. – Pär Wieslander Dec 21 '10 at 12:58
34

You could print a backspace character ('\b'):

for i in xrange(20):
    print '\ba',

result:

aaaaaaaaaaaaaaaaaaaa
mpontillo
  • 13,559
  • 7
  • 62
  • 90
Lucas Moeskops
  • 5,445
  • 3
  • 28
  • 42
30

Python 3.x:

for i in range(20):
    print('a', end='')

Python 2.6 or 2.7:

from __future__ import print_function
for i in xrange(20):
    print('a', end='')
codeape
  • 97,830
  • 24
  • 159
  • 188
10

If you want them to show up one at a time, you can do this:

import time
import sys
for i in range(20):
    sys.stdout.write('a')
    sys.stdout.flush()
    time.sleep(0.5)

sys.stdout.flush() is necessary to force the character to be written each time the loop is run.

daviewales
  • 2,144
  • 21
  • 30
7

Just as a side note:

Printing is O(1) but building a string and then printing is O(n), where n is the total number of characters in the string. So yes, while building the string is "cleaner", it's not the most efficient method of doing so.

The way I would do it is as follows:

from sys import stdout
printf = stdout.write

Now you have a "print function" that prints out any string you give it without returning the new line character each time.

printf("Hello,")
printf("World!")

The output will be: Hello, World!

However, if you want to print integers, floats, or other non-string values, you'll have to convert them to a string with the str() function.

printf(str(2) + " " + str(4))

The output will be: 2 4

  • Do you say that I can output an infinite amount of text in same time as outputting one character? – ctrl-alt-delor Jan 01 '15 at 13:35
  • When I redefined printf to stdout.write, my stdout.write seems to be printing the number of chartacters the string is: "Hello,6" What gives? What's going on? And how do I stop it? – Tom Aug 20 '16 at 00:13
  • 1
    Also, can you explain what you mean by O(1) O(n)? I don't understand what that refers to – Tom Aug 20 '16 at 00:32
  • @Tom It's referring to complexity (Big O notation) as a reflection of the _cost_ of the operation. O(1) is constant time - _ideal_ - and O(n) is linear time - _okay_ but way too expensive for something so simple. Although, for small things, the time you spend using your brain to worry about these things is more computationally wasteful than just using string concatenation. – Benjamin R Sep 21 '16 at 22:17
6

without what? do you mean

>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa

?

Ant
  • 5,151
  • 2
  • 26
  • 43
6

Either what Ant says, or accumulate into a string, then print once:

s = '';
for i in xrange(20):
    s += 'a'
print s
Community
  • 1
  • 1
jensgram
  • 31,109
  • 6
  • 81
  • 98
3

this is really simple

for python 3+ versions you only have to write the following codes

for i in range(20):
      print('a',end='')

just convert the loop to the following codes, you don't have to worry about other things

Shad Munir
  • 91
  • 4
2

WOW!!!

It's pretty long time ago

Now, In python 3.x it will be pretty easy

code:

for i in range(20):
      print('a',end='') # here end variable will clarify what you want in 
                        # end of the code

output:

aaaaaaaaaaaaaaaaaaaa 

More about print() function

print(value1,value2,value3,sep='-',end='\n',file=sys.stdout,flush=False)

Here:

value1,value2,value3

you can print multiple values using commas

sep = '-'

3 values will be separated by '-' character

you can use any character instead of that even string like sep='@' or sep='good'

end='\n'

by default print function put '\n' charater at the end of output

but you can use any character or string by changing end variale value

like end='$' or end='.' or end='Hello'

file=sys.stdout

this is a default value, system standard output

using this argument you can create a output file stream like

print("I am a Programmer", file=open("output.txt", "w"))

by this code you will create a file named output.txt where your output I am a Programmer will be stored

flush = False

It's a default value using flush=True you can forcibly flush the stream

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
SHAH MD IMRAN HOSSAIN
  • 2,558
  • 2
  • 25
  • 44
2

as simple as that

def printSleeping():
     sleep = "I'm sleeping"
     v = ""
     for i in sleep:
         v += i
         system('cls')
         print v
         time.sleep(0.02)
tlejmi
  • 526
  • 8
  • 13
0

in python 2, add (,) after print and it will act as end='' in python 3. But for space in between, you are still off to use future version of the print.

for x in ['a','b','c','d']:
   print(x),
mehdi
  • 2,703
  • 1
  • 13
  • 15