正确对齐python

时间:2015-07-13 17:02:12

标签: python python-3.x

如何证明此代码的输出是正确的?

N = int(input())
case = '#'
print(case)

for i in range(N):
    case += '#'
    print(case)

5 个答案:

答案 0 :(得分:13)

您可以format >使用N = 10 for i in range(1, N+1): print('{:>10}'.format('#'*i)) 来对齐

         #
        ##
       ###
      ####
     #####
    ######
   #######
  ########
 #########
##########

输出

rjust

您可以使用for i in range(1, N+1): print(('#'*i).rjust(N)) 以编排方式计算出正确对齐的距离。

my_string = 'foo'
print my_string.rjust(10)
'       foo'

答案 1 :(得分:7)

好像你可能正在寻找rjust:

https://docs.python.org/2/library/string.html#string.rjust

Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -location 'Default Web Site' -filter "system.webServer/security/ipSecurity" -name "enableReverseDns" -value "True"

答案 2 :(得分:3)

string.format()方法将此作为其语法的一部分。

print "{:>10}".format(case)

字符串中的数字告诉python字符串应该有多长字符,即使它大于case的长度。并且大于号告诉它在该空间内右对齐case

答案 3 :(得分:1)

N = int(input())
for i in range(N+1):
    print(" "*(N-i) + "#"*(i+1))

打印正确数量的空格,然后输入正确数量的"#"字符。

答案 4 :(得分:0)

使用f弦和联接的一个衬里:

print("\n".join([f"{'#' * i:>10}" for i in range(1, 11)]))

输出:

         #
        ##
       ###
      ####
     #####
    ######
   #######
  ########
 #########
##########

如果要包含行号,可以执行以下操作:

print("\n".join([f"{i:<3}{'#' * i:>10}" for i in range(1, 11)]))

输出:

1           #
2          ##
3         ###
4        ####
5       #####
6      ######
7     #######
8    ########
9   #########
10 ##########
相关问题