可重复对齐:错误“字符串无法从手动字段指定切换为自动字段编号”

时间:2018-11-21 12:37:57

标签: python string format string-formatting

这是我的代码:

def f(n):


    if n == 0:
        return 1
    else:
        result = 1
        for i in range(1,n+1):
            result = result * i
        return result





def a(n):
    sum = 0
    z = 0
    for i in range(n+1):
        sum += f(i)
        print('{0:<4}! = {1:<4}  no.multi. ={} sum of {}!  = {}   no.multi. = {}'.format(i,f(i),i,i,sum,z))
        z = z + (i+1)


a(19)

我需要获得以下输出:here

但是相反,我得到了一种像this

的金字塔

我试图在方括号内进行格式化,但始终收到错误:“无法从手动字段指定切换为自动字段编号”  预先谢谢

1 个答案:

答案 0 :(得分:0)

我声明了变量strong_i,它是带有i的{​​{1}}的字符串,在选择!时用!打印空格时要考虑到i {1}}。

!

输出:

def f(n):
    if n == 0:
        return 1
    else:
        result = 1
        for i in range(1,n+1):
            result = result * i
        return result

def a(n):
    sum = 0
    z = 0
    for i in range(n+1):
        sum += f(i)
        strong_i = str(i) + '!'
        print('{0:<4}= {1:<20}  no.multi. = {2:<2} sum of {3:<3}  = {4:<20}   no.multi. = {5}'.format(strong_i,f(i),i,strong_i,sum,z))
        z = z + (i+1)

a(19)