Python,在end =“”之后开始一个新行

时间:2017-03-24 06:49:25

标签: python

目前,我有这段代码:

for i in range(lower_limit, upper_limit+1): 

    for j in range(0,len(prime_number)):
        for k in range(0 + j,len(prime_number)):
            if i == prime_number[j] + prime_number[k] and i % 2 == 0:  

                print(i, "=", prime_number[j], "+", prime_number[k])

打印:

10 = 3 + 7 
10 = 5 + 5 
12 = 5 + 7 
14 = 3 + 11 
14 = 7 + 7 

我需要结果如下:

10 = 3 + 7 = 5 + 5
12 = 5 + 7
14 = 3 + 11 = 7 + 7

我知道我必须以某种方式使用end =“”然后它只打印一行中的所有数字。我该怎么办?

1 个答案:

答案 0 :(得分:3)

使用end= " "和外部循环末尾的空print()来结束该行。

例如:

>>> for i in range(3):
...     print("foo", end = " ")
...     print("bar", end = " ")
...     print()
...
foo bar
foo bar
foo bar

特别针对您的情况:

for i in range(lower_limit, upper_limit+1): 
    print(i, end = " ") 
    for j in range(0,len(prime_number)):
        for k in range(0 + j,len(prime_number)):
            if i == prime_number[j] + prime_number[k] and i % 2 == 0:  

                print("=", prime_number[j], "+", prime_number[k],end = " ")
    print()