Python Print parameter end

前端 未结 3 385
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 12:50

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

相关标签:
3条回答
  • 2021-01-27 13:20

    you can use an if statement to check if its the last number:

    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='')
    
    0 讨论(0)
  • 2021-01-27 13:30

    The inevitable pythonic one-liner:

    print(*map(fibonaci_num, range(N)), sep=' add -> ')
    
    0 讨论(0)
  • 2021-01-27 13:34

    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 讨论(0)
提交回复
热议问题