【问题标题】:Reducing spaces between the character python [duplicate]减少字符python之间的空格[重复]
【发布时间】:2018-04-25 22:27:48
【问题描述】:

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

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
     #
    ##
   ###
  ####
 #####
######

正如人们所看到的,我的输出带有空格,并且按照原始模式是不可接受的。请帮忙。

【问题讨论】:

  • @pissall 那些是用来做楼梯的,不是为了“#”之间的空间
  • 顺便说一句,您应该认真考虑学习 Python 3。Python 2 将在 2020 年正式结束生命周期。
  • 链接的问题显示了使用print 语句和print 函数执行此操作的各种方法。但是,最好使用''.join(element) 执行此操作。或者,您可以使用字符串乘法而不是循环来生成字符串。
  • @PM2Ring 还有 3 年... :D :P

标签: python python-2.7


【解决方案1】:

如果你坚持:

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

【讨论】:

    【解决方案2】:

    您有答案,但在原始代码中您使用终端“,”来禁止换行。这会在您打印的内容之后添加一个空格。当然是在 python 2 中。

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 2023-03-22
      • 2019-04-23
      • 2017-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多