简体   繁体   English

如何删除最后一个数字后的多余空格

[英]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输入: 5
Output: 0 1 1 2 3 Output: 0 1 1 2 3
I'm printing an extra space after the last number.我在最后一个数字之后打印了一个额外的空格。

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. (这是您无论如何都应该做的事情,但在这种情况下也会发生这种情况,以便更容易解决问题。)例如,我们可以使用生成器来yield多个值。 Notice that we don't need to handle any special cases, and we can also use the pack-unpack idiom for multiple assignments :请注意,我们不需要处理任何特殊情况,我们也可以使用 pack-unpack 习惯用法进行多次赋值

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 sep arator for print rather than the end , and passing each of the values as a separate argument.现在我们可以通过使用sep print而不是end来显示这些由空格分隔的值,并将每个值作为单独的参数传递。 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

A @Carcigenicate suggested you can use a list, @Carcigenicate 建议您可以使用列表,

In the following code have just replaced the print statements with list.append()在下面的代码中刚刚用list.append()替换了print语句

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: 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 .正如您在 output 中看到的那样,最后一个数字13之后没有多余的空间,我在13之后打印了h

hope this helps you!希望这对你有帮助!

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

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