0

I can't get over this little problem.

enter image description here

The second is right.

How can i print without spaces?

def square(n):
    for i in range(n):
        for j in range(n):
            if i==0 or j==0 or i==n-1 or j==n-1: print "*",
            else: print "+",
    print

thanks for help!

1
  • I would build the whole line as a string before printing it. Or use Python 3, where you can set the "end" to ''. Oct 29, 2013 at 13:09

3 Answers 3

10

By not using print plus a comma; the comma will insert a space instead of a newline in this case.

Use sys.stdout.write() to get more control:

import sys

def square(n):
    for i in range(n):
        for j in range(n):
            if i==0 or j==0 or i==n-1 or j==n-1: sys.stdout.write("*")
            else: sys.stdout.write("+")
        print

print just writes to sys.stdout for you, albeit that it also handles multiple arguments, converts values to strings first and adds a newline unless you end the expression with a comma.

You could also use the Python 3 print() function in Python 2 and ask it not to print a newline:

from __future__ import print_function

def square(n):
    for i in range(n):
        for j in range(n):
            if i==0 or j==0 or i==n-1 or j==n-1: print("*", end='')
            else: print("+", end='')
        print()

Alternatively, join the strings first with ''.join():

def square(n):
    for i in range(n):
        print ''.join(['*' if i in (0, n-1) or j in (0, n-1) else '+' for j in xrange(n)])
2
  • We can remove [ ] in Join and add ( ) for print function call for Python 3... Oct 29, 2013 at 13:34
  • 1
    @GrijeshChauhan: See stackoverflow.com/a/9061024; for a ''.join() call it is faster to use a list comprehension instead of a generator expression.
    – Martijn Pieters
    Oct 29, 2013 at 13:37
2

Can you try to use sys.stdout.write("+") instead of print "+" ?

0

In python 3 you can overwrite the print behaviour, here this will solve your problem:

print("+", end="")
1
  • 1
    Not in Python 2, where print is a statement, not a function. Unless you tell the Python compiler you wanted to use the function instead (by using from __future__ import print_function).
    – Martijn Pieters
    Oct 29, 2013 at 13:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.