Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding horizontal space between data on a Read only script

I need my output to look nice, and it looks very sloppy.

--------Current output---------

Below are the players and their scores

John Doe 120
Sally Smooth 115

----------End current output----------

My desired output follows

-------Desired output-----------------

Below are the players and their scores

John Doe         120
Sally Smooth     115

--------End desired output-------------

my current code follows;

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()
like image 681
Slow Poke Avatar asked May 14 '26 03:05

Slow Poke


2 Answers

Try using the tab character to format your spaces better.

print(name + "\t" + score)

This should give you something closer to your desired output. But you may need to use two if some names are long.

like image 186
Andrew Hewitt Avatar answered May 16 '26 15:05

Andrew Hewitt


You can add the names and the scores to a list and then print it as a table as

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

Note: This depends on str.format()

This code will output:

           jane doe            102
       sally smooth            106
like image 35
Moonstruck Avatar answered May 16 '26 16:05

Moonstruck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!