質問

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!

役に立ちましたか?

解決

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)])

他のヒント

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

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

print("+", end="")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top