【问题标题】:Adding horizontal space between data on a Read only script在只读脚本上的数据之间添加水平空间
【发布时间】:2017-02-10 21:17:02
【问题描述】:

我需要我的输出看起来不错,而且看起来很草率。

--------电流输出---------

Below are the players and their scores

John Doe 120
Sally Smooth 115

---------结束当前输出----------

我想要的输出如下

-------期望的输出------

Below are the players and their scores

John Doe         120
Sally Smooth     115

--------结束所需的输出-------------

我当前的代码如下;

def main():

     # opens the "golf.txt" file created in the Golf Player Input python
     # in read-only mode
     infile = open('golf.txt', 'r')

     print("Below are the players and their scores")
     print()

     # reads the player array from the file
     name = infile.readline()

     while name != '':

          # reads the score array from the file
          score = infile.readline()

          # strip newline from field
          name = name.rstrip('\n')
          score = score.rstrip('\n')
          # prints the names and scores
          print(name + " " + score)

          # read the name field of next record
          name = infile.readline()

     # closes the file    
     infile.close()


 main()

【问题讨论】:

    标签: python readfile


    【解决方案1】:

    尝试使用制表符更好地格式化您的空格。

    print(name + "\t" + score)
    

    这应该会给你一些更接近你想要的输出的东西。但是,如果某些名称很长,您可能需要使用两个。

    【讨论】:

    • 以下是球员和他们的分数 John Doe 120 Sally Smooth 115 >>>
    • 事后您可能还想尝试安装和使用“制表”,这将为您提供更好的输出,而无需手动计算名称大小。 :)
    【解决方案2】:

    您可以将名称和分数添加到列表中,然后将其打印为表格

    import numpy as np
    name_list = ['jane doe' ,'sally smooth']
    score = np.array([[102,],[106,]]) #make a numpy array 
    row_format ="{:>15}" * (len(name_list))
    for name, row in zip(name_list, score):
        print(row_format.format(name, *row))
    

    注意:这取决于 str.format()

    这段代码将输出:

               jane doe            102
           sally smooth            106
    

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多