Python - 删除输出中的空格

Python - Removing whitespace on output

所以,我有这个代码:

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

有效,但在输出中,最后一个数字后有一个白色space。我需要摆脱最后的白色space。我的输出需要显示在同一行上,由空格 space 分隔。最后一个值后不应有space。

这里有一个例子:(n 是输入,所以假设 n = 5)

0 1 1 2 3

我试过 .strip、.join,但 none 成功了。我需要做什么才能获得正确的输出?很抱歉,如果这个问题太简单了,我是 python 的新人。

编辑:编辑2:

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

您正在使用 end 参数自行添加尾随 space。

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

表示打印 a' ' 结尾。删除 end 参数,尾随的 space 将不再打印(默认的 '\n' 将被打印)。有关详细信息,请参阅 the docs for print()

另请注意,end 参数不会影响您正在打印的字符串,即 a 不受 end 影响。如果字符串 a 中有尾随 space,则 a.strip() 将删除 space。在您的情况下,strip() 没有删除它的原因是 space 不在您正在打印的字符串中,而是通过 print() 函数添加到视觉输出中.

更新:

这很难说,因为在您编辑的代码片段之前或之后发生的事情是个谜,但听起来您想做类似的事情:

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))