Python - spaces

亡梦爱人 提交于 2019-12-11 19:57:52

问题


I can't get over this little problem.

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:


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:


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




回答3:


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

print("+", end="")


来源:https://stackoverflow.com/questions/19659100/python-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!