【问题标题】:how to remove a space from a line如何从一行中删除一个空格
【发布时间】:2020-10-02 14:44:12
【问题描述】:

我的程序在每一行之后打印一个额外的空格。我想删除每行末尾的多余空格。

x, y = map(int, input().split())
count = 0
while count < (y//x):
    start = count*x + 1
    end = (count + 1) * x + 1
    for i in range(start,end,1):
        print(i,end=" ")
    print("")
    count+=1

输入: 3 99

输出:

1 2 3 
4 5 6
7 8 9
.....

每行结束后我打印了一个额外的空格,我怎样才能删除这个空格?

【问题讨论】:

    标签: python python-3.x output


    【解决方案1】:

    我们将数字作为一组打印并控制分隔符和结束字符的更简单方法如何:

    x, y = map(int, input().split())
    
    count = 0
    
    while count < y // x:
        start = count * x + 1
        end = start + x
    
        print(*range(start, end), sep=" ")
    
        count += 1
    

    【讨论】:

      【解决方案2】:

      创建一个临时数组变量来存储您的值。然后一次性打印数组,如图所示。

      x, y = map(int, input().split())
      count = 0
      while count < (y//x):
          start = count*x + 1
          end = (count + 1) * x + 1
          temp_array = []
          for i in range(start,end,1):
              temp_array.append(i)
          print(*temp_array, sep = " ", end = "\n")
          count+=1
      

      【讨论】:

        【解决方案3】:

        只需少迭代一次,然后以正常结束而不是空打印输出

        x, y = map(int, input().split())
        count = 0
        while count < (y//x):
            start = count*x + 1
            end = (count + 1) * x + 1
            for i in range(start,end - 1,1):
                print(i,end=" ")
            print(end - 1)
            count+=1
        

        【讨论】:

        • 它不工作,它给出了这个输出。 1 2 44 5 77 8 10
        猜你喜欢
        • 2013-10-02
        • 2018-01-09
        • 2013-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-18
        相关资源
        最近更新 更多