减少角色python之间的空格

时间:2017-11-13 09:29:11

标签: python python-2.7

我正在尝试打印楼梯图案。我编写的代码如下:

def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        for element in reversed_array:
            print "{}".format(element),
        print


_n = int(raw_input().strip("\n"))
StairCase(_n)

我的输出为:

6
          #
        # #
      # # #
    # # # #
  # # # # #
# # # # # #

预期输出为:

6
     #
    ##
   ###
  ####
 #####
######

正如我可以看到我的输出是空格的,并且根据原始模式是不可接受的。请帮助。

2 个答案:

答案 0 :(得分:5)

如果你坚持:

def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        print ''.join(reversed_array)

但更简单的方法就是:

def StairCase_new(n):
    for i in range(1, n + 1):
        print ' '*(n-i) + '#'*i

答案 1 :(得分:1)

您有答案,但在原始代码中,您使用终端&#39;,&#39;抑制换行符。在您打印的东西之后添加一个空格。当然是在python 2中。