desperate desperate - 1 month ago 15
Python Question

Python - Removing whitespace on output

So, I have this code:

print("%d" % a, end=(" "))


It works, but in the output, there's a whitespace after the last number. I need to get rid of the last whitespace. My output needs to be shown on the same line, separated by a blank space. There should be no space after the last value.

Here's an example: (n is input, so suppose n = 5)

0 1 1 2 3


I've tried .strip, .join, but none of them worked. What do i have to do to get the right output? I'm sorry if this is too much of a simple question, I'm new in python.

edit: edit2:

a, b, i = 0, 1, 0
n=int(input())
for j in range(0, n):
while i < n:
print("%d" % a)
a, b = b, a + b
i += 1

Answer

You are adding the trailing space yourself with the end argument.

print("%d" % a, end=(" "))

Means print a ending in a ' '. Remove the end argument and the trailing space will no longer be printed (the default '\n' will be printed instead). See the docs for print() for more details.

Note also, that the end argument does not affect the string you are printing, i.e., a is not affected by end. If there is a trailing space in a string a, then a.strip() will remove that space. The reason it doesn't get removed by strip() in your case is that the space is not in the string you are printing, but instead is added to the visual output by the print() function.

Update:

It is hard to say, because it is a mystery what happens before or after the code snippet in your edit, but it sounds like you want to do something like:

a, b, i = 0, 1, 0
n=int(input())
nums = []
for j in range(0, n):
    while i < n:
        nums.append(str(a))
        ...
        # Based on your desired output, 
        # I assume you modify the value of `a` somwhere in here
        ...
print(' '.join(nums))
Comments