Search code examples
pythonpython-3.xleaderboardordinals

How to add ordinal numbers to the start of each line in text file


I have a leaderboard for a game stored in a file. The format of the file is this:

bob has 46 points fred has 0 points leo has 27 points

I have this code to display the scores in order from ascending to descending order:

if ens == "s":
    print("\n"+"LeaderBoard: "+"\n")
    f = open("scores.txt","r")
    lines = list(f) #create a list of strings
    f.close() #don't forget to close our files when we're done. It's good practice.
    modified_lines = [] #empty list to put our modified lines in (extracted number, original line)
    for line in lines: #iterate over each line
        if line.strip(): #if there's anything there after we strip away whitespace
            score = line.split(' ')[2] #split our text on every space and take the third item
            score = int(score) #convert the string of our score into a number
            modified_lines.append([score, line]) #add our modified line to modified_lines

    #sort our list that now has the thing we want to sort based on is first
    sorted_modified_lines = sorted(modified_lines, reverse = True )

    #take only the string (not the number we added before) and print it without the trailing newline.
    for line in sorted_modified_lines: print(line[1].strip()+"\n")

output:

bob has 46 points leo has 27 points fred has 0 points

What I want is for the scores to displayed with ordinal numbers in front of the scores like this:

1st. bob has 46 points 2nd. leo has 27 points 3rd. fred has 0 points

I have looked at other post that show how to display ordinal numbers but I still have no idea on how to do this.


Solution

  • Something like this...

    def ordinal_string(i):
       if i >= 10 and i <= 20:
          suffix = 'th'
       else:
         il = i % 10
         if il == 1:
            suffix = 'st'
         elif il == 2:
            suffix = 'nd'
         elif il == 3:
            suffix = 'rd'
         else:
            suffix = 'th'
       return str(i) + suffix + '. '
    

    then:

    for i, line in enumerate(sorted_modified_lines): print(ordinal_string(i+1) + line[1].strip()+"\n")