【问题标题】:Python 3.5 String formattingPython 3.5 字符串格式化
【发布时间】:2015-11-04 03:59:21
【问题描述】:

如何用百分比将行左对齐,让输出看起来不错?

问题似乎出在下面一行:

print("{:>9}%".format(i*10), end='')

程序的输入输出示例:

How many columns should there be (1-6) ? 4
How many rows should there be in the table? 5
Original   Price discounted by
   price       20%       30%       40%       50%
    5.00     4.00    3.50    3.00    2.50 
   10.00     8.00    7.00    6.00    5.00 
   15.00    12.00   10.50    9.00    7.50 
   20.00    16.00   14.00   12.00   10.00 
   25.00    20.00   17.50   15.00   12.50 

目标:

How many columns should there be (1-6) ? 4
How many rows should there be in the table? 5
Original   Price discounted by
   price      20%     30%     40%     50%
    5.00     4.00    3.50    3.00    2.50 
   10.00     8.00    7.00    6.00    5.00 
   15.00    12.00   10.50    9.00    7.50 
   20.00    16.00   14.00   12.00   10.00 
   25.00    20.00   17.50   15.00   12.50 

代码:

column = int(input("How many columns should there be (1-6) ? "))
row = int(input("How many rows should there be in the table? "))

initialPrice = 5.00
initialDiscount = 10.0

print("{0:>8} {1:>21}".format("Original", "Price discounted by"))
print("{0:>8}".format("price"), end='')
for i in range(2,column+2):
    print("{:>9}%".format(i*10), end='')
print()

for y in range (1,row+1):
    print("{0:>8.2f} ".format(y * initialPrice), end='')
    for x in range (2,column+2):
        print("{0:>8.2f}".format(y * initialPrice * (1 - x*0.1)), end='')
    print()

【问题讨论】:

    标签: string python-3.x formatting


    【解决方案1】:

    经过大量的反复试验,我设法得到了它。改变这一行

    print("{0:>8.2f}".format(y * initialPrice * (1 - x*0.1)), end='')
    

    到这个。改变的是间距值 {0:>8.2f} -> {0:>9.2f}end 现在是一个带有空格 end=' ' 的字符串。

    print("{0:>9.2f}".format(y * initialPrice * (1 - x*0.1)), end=' ')
    

    您可以将间距值设置为任何您想要的数字,它只需要与用于打印百分比的值相匹配。

    或者,您可以在打印价格上显示end=' '

    完整代码(替换行已注释):

    column = int(input("How many columns should there be (1-6) ? "))
    row = int(input("How many rows should there be in the table? "))
    
    initialPrice = 5.00
    initialDiscount = 10.0
    
    print("{0:>8} {1:>21}".format("Original", "Price discounted by"))
    print("{0:>8}".format("price"), end='')
    #print("{0:>8}".format("price"), end=' ')
    for i in range(2,column+2):
        print("{:>9}%".format(i*10), end='')
    print()
    
    for y in range (1,row+1):
        print("{0:>8.2f} ".format(y * initialPrice), end='')
        for x in range (2,column+2):
            print("{0:>9.2f}".format(y * initialPrice * (1 - x*0.1)), end=' ')
            #print("{0:>9.2f}".format(y * initialPrice * (1 - x*0.1)), end='')
        print()
    

    【讨论】:

      猜你喜欢
      • 2019-11-28
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 2016-06-21
      相关资源
      最近更新 更多