Python - 空格 [英] Python - spaces

查看:61
本文介绍了Python - 空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法克服这个小问题.

I can't get over this little problem.

第二个是对的.

如何在没有空格的情况下打印?

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

感谢您的帮助!

推荐答案

通过不使用 print 加逗号;在这种情况下,逗号将插入一个空格而不是换行符.

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

使用 sys.stdout.write() 获得更多控制:

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 只是为您写入 sys.stdout,尽管它还处理多个参数,首先将值转换为字符串并添加换行符,除非您以逗号.

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.

您也可以使用 Python 3 print() function 在 Python 2 中并要求它不打印换行符:

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

或者,先用 ''.join() 连接字符串:

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

这篇关于Python - 空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆