Shakib
Shakib

Reputation: 27

how to remove the extra space after last number

In my program, I am printing an extra space after the last number. How can I remove that?

def fibonacci(n):
a = 0
b = 1
if n == 1:
    print(a, end=' ')
else:    
    print(a, end=' ')
    print(b, end=' ')
    for i in range(2, n):
        c = a + b
        a = b
        b = c
        print(c, end=' ')

fibonacci(int(input()))

Input: 5
Output: 0 1 1 2 3
I'm printing an extra space after the last number.

Upvotes: 0

Views: 878

Answers (2)

Prathamesh
Prathamesh

Reputation: 1057

A @Carcigenicate suggested you can use a list,

In the following code have just replaced the print statements with list.append()

def fibonacci(n):
    l1=[]
    a = 0
    b = 1
    if n == 1:
        print(a, end=' ')
        l1.append(str(a))

    else:    
        l1.append(str(a))
        l1.append(str(b))
        for i in range(2, n):
            c = a + b
            a = b
            b = c
            l1.append(str(c))
    tr=" ".join(l1)
    print(tr,end='')
    print('h',end='')

fibonacci(int(input()))

output:

8
0 1 1 2 3 5 8 13h

as you can see in the output there is no extra space after last number 13 and i have printed h after 13.

hope this helps you!

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61508

Separate the process of generating the numbers, from the process of printing them. (This is something you should do anyway, but it also happens in this case to make it easier to solve the problem.) For example, we can use a generator to yield multiple values. Notice that we don't need to handle any special cases, and we can also use the pack-unpack idiom for multiple assignments:

def fibonacci(n):
    a, b = 1, 1
    for i in range(n):
        yield a
        a, b = b, a + b

Now we can display these values separated by spaces by using the separator for print rather than the end, and passing each of the values as a separate argument. To do that, we need explicit unpacking with *. It looks like:

print(*fibonacci(10), sep=' ')

And we get the desired result, with no trailing space:

1 1 2 3 5 8 13 21 34 55

Upvotes: 1

Related Questions