在循环中的不同行上打印值时,如何避免在上一次迭代后打印换行符?

时间:2019-03-26 12:17:22

标签: python printing

我试图遍历并打印每个数字范围内素数的元素。我想在换行中打印它们,但最后一个要打印的元素的末尾不需要换行。

def prime_in_range():

    lower=int(input())
    upper=int(input())
    if 1 <= lower   <= 10000 and 1 <= upper <= 10000:

        for num in range(lower, upper + 1):
            # prime numbers are greater than 1
            if num > 1:
                for i in range(2, num):
                    if (num % i) == 0:
                        break
                else:
                    print(num)  #changing this to print(num,end='') prints everything in same line
prime_in_range()

输入为1和10时,我需要输出为:

2
3
5
7

但是默认情况下,我会在换行符结尾

2
3
5
7

并使用print(num,end='')取得以下内容:

2357

3 个答案:

答案 0 :(得分:5)

一种解决方法是使您的函数产生输出值,并使调用者解包并打印值,其中换行符为end='',换行符为空,而空字符串为以def prime_in_range(lower, upper): if 1 <= lower <= 10000 and 1 <= upper <= 10000: for num in range(lower, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: yield num print(*prime_in_range(2, 7), sep='\n', end='') 结尾的行代替:

def aliased_aggr(aggr, name):
    if isinstance(aggr,str):
        def f(data):
            return data.agg(aggr)
    else:
        def f(data):
            return aggr(data)
    f.__name__ = name
    return f

答案 1 :(得分:0)

您可以将数字存储在列表中,然后将列表转换为用新行分隔的字符串。

def prime_in_range():

    lower=int(input())
    upper=int(input())
    temp = []
    if 1 <= lower   <= 10000 and 1 <= upper <= 10000:

        for num in range(lower, upper + 1):
            # prime numbers are greater than 1
            if num > 1:
                for i in range(2, num):
                    if (num % i) == 0:
                        break
                else:
                    # print(num)  #changing this to print(num,end='') prints everything in same line
                    temp.append(num)
    print('\n'.join(str(i) for i in temp))
prime_in_range()

答案 2 :(得分:0)

谢谢大家。我对解决方案进行了一些调整,以分别打印最后一个项目,并获得了所需的结果(不确定这是否是最好的解决方案): 附言必须从STDIN接受输入,而不传递函数调用。

def prime_in_range():
    lower=int(input())
    upper=int(input())
    l=[]
    if 1 <= lower   <= 10000 and 1 <= upper <= 10000:

        for num in range(lower, upper + 1):
            # prime numbers are greater than 1
            if num > 1:
                for i in range(2, num):
                    if (num % i) == 0:
                        break
                else:
                    l.append(num)
                    #print(num)
                    #print(l)
    llen=(len(l))

    for i in range(llen-1):
        print(l[i])
    print(l[-1],end='')

输出:

2
3
5
7
Process finished with exit code 0