关于打印输出的格式(python)

时间:2016-11-18 23:35:12

标签: python formatting string-formatting

我一直在研究列出产品的程序(包括成本和数量),它们分别存储在3个不同的列表中。

然而,我无法弄清楚如何做,是对齐打印输出

while valid ==1 :
    if user_choice == 's':
        user_product = str(input("Enter a product name: "))
        valid = 2
    elif user_choice == 'l':
        print ("Product" + "     " + "Quantity" +"     "+ "Cost")
        c = 0
        while c < len(product_names):
            print (product_names[c] + "    " + str(product_costs[c]) + "     "+ str(quantity[c]))
            c +=1
            valid = 0
        break
        valid = 0

所以基本上我不确定如何在第6行和第6行实际输出 因为产品名称的长度不同,成本和数量也有所不同,所以第9行要对齐,因为我会得到一个杂乱无章的输出。 任何人都可以教我如何将它们全部正确地对齐,以便它们可以 看起来像一张桌子?

非常感谢!

1 个答案:

答案 0 :(得分:-1)

这是您想要的,完全按照规定的顺序

n = -1                                 # Intentionally an incorrect value

# Ask user for the number while he/she doesn't enter a correct one

while n < 10:
    n = int(input("Enter an integer number greater or equal 10: "))


# Preparation for Sieve of Eratosthenes

flags_list = ["P"]                     # 1st value
flags_list = flags_list * (n + 1)      # (n + 1) values

flags_list[0] = "N"                    # 0 is not a prime number
flags_list[1] = "N"                    # 1 is not a prime number, too


# Executing Sieve of Eratosthenes

for i in range(2, n + 1):
    if flags_list[i] == "P":
        for j in range(2 * i, n + 1, i):
            flags_list[j] = "N"


# Creating the list of primes from the flags_list

primes = []                            # Empty list for adding primes into it

for i in range(0, n + 1):
    if flags_list[i] == "P":
        primes.append(i)


# Printing the list of primes

i = 0                                  # We will count from 0 to 9 for every printed row
print()

for prime in primes:
    if i < 10:
        print("{0:5d}".format(prime), end="")
        i = i + 1
    else:
        print()                        # New line after the last (10th) number
        i = 0

===========您的EDITED,完全其他问题的答案:===========

===========(请不要这样做,而是创建一个问题。)===========

替换这部分代码:

print ("Product" + "     " + "Quantity" +"     "+ "Cost")
c = 0
while c < len(product_names):
    print (product_names[c] + "    " + str(product_costs[c]) + "     "+ str(quantity[c]))
    c +=1

有了这个(使用原始缩进,因为它在Python中很重要):

print("{:15s} {:>15s} {:>15s}".format("Product", "Quantity", "Cost"))

for c in range(0, len(product_names)):
    print("{:15s} {:15d} {:15d}".format(product_names[c], quantity[c], product_costs[c]))

(我将您的订单在第二个print更改为名称,数量,费用 - 与您的第一个print相对应。)

您可能希望将15更改为其他数字(甚至可以单独更改为12 9 6),但三位数print中的em>必须与第二个print()中的相同。

解释:

{: }print方法中.format()语句中列出的单个字符串/整数的占位符。

占位符中的数字表示为适当值保留的长度。

可选>表示输出在其保留空间中正确对齐,因为文本的默认对齐方式是到左侧和数字在右边。 (是的,<表示对齐且^居中。)

占位符中的字母表示s表示字符串,d(作为“十进制”)表示整数 - 对于数字,也可以是f(作为“浮点数”)其中包含小数点 - 在这种情况下,输出中{:15.2f}小数位(来自保留2)将为15

对于占位符中的符号df,会自动自动执行从到字符串的转换,因此此处不使用str(some_number)

<强>附录:

如果您有时间,请复制/粘贴您编辑的版本作为新问题,然后将此问题还原为原始状态,因为人们评论/回答了原始问题。我会找到你的新问题并对我的回答做同样的事情。谢谢!