简体   繁体   English

Python Print参数结束

[英]Python Print parameter end

How to remove the last "add -->" from the output when using end, i am not using sep here, bcoz sep will not have any effect here , as the print statement prints just 1 item at a time here and ends with incr of i 使用end时如何从输出中删除最后一个“ add->”,我在这里不使用sep,bcoz sep在这里不会有任何效果,因为print语句一次只打印1个项目,并以incr结尾我的

def fibonaci_num(n):
    if n <= 1:
        return n
    else:
        return fibonaci_num(n-1) + fibonaci_num(n-2)

N = 10

for i in range(N):
    print(fibonaci_num(i), end=' add -> ')

my output 我的输出

0 add -> 1 add -> 1 add -> 2 add -> 3 add -> 5 add -> 8 add -> 13 add -> 21 add -> 34 add -> 

you can use an if statement to check if its the last number: 您可以使用if语句检查其最后一个数字:

def fibonaci_num(n):
    if n <= 1:
        return n
    else:
        return fibonaci_num(n-1) + fibonaci_num(n-2)

N = 10

for i in range(N):
    print(fibonaci_num(i), end='')
    if i != N-1:
        print(' add -> ', end='')

不可避免的pythonic一线:

print(*map(fibonaci_num, range(N)), sep=' add -> ')

Here I've simplified answer using ternary operator. 在这里,我使用三元运算符简化了答案。 May it will be helpful and better. 希望它会有所帮助并且变得更好。

def fib(n):    
    a, b = 0, 1
    while a < n:
        endstatement = '-' if (b < n) else ''
        print(a, end=endstatement)
        a, b = b, a+b
    print()


# Now call the function:
fib(1000)

Result : 0-1-1-2-3-5-8-13-21-34-55-89-144-233-377-610-987 结果0-1-1-2-3-5-8-13-21-34-55-89-144-233-377-610-987

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM