How to strip letters off a string with numbers, so that it can be changed to int and sorted

87 Views Asked by At

I am making a dice rolling game where the scores and players have to be stored in an array, and then printed out in order as a scoreboard. I can do all of this but sorting the scoreboard.

I have worked out that I need to strip the letters from the string (player1 37 to just 37). The current code that I'm using is delchars = Player1.join(c for c in map(chr, range(256)) if not c.isalnum()) but it doesn't seem to be working, anyone know what to do.

#code for entering Player1 
let= True
while let == True:
    delay_print("player 1 enter your username\n")
    Player1 = input()
    if len(Player1) > 20 or len(Player1) < 3:
        print("That is too long or too short, please try again") 
    else:
        let = False
#code for entering Player2
tel = True
while tel == True:
    delay_print("player 2 enter your username\n")
    Player2 = input()
    if len(Player2) > 20  or len(Player2) < 3:
        print("That is too long, or too short, please try again")
    else:
        tel = False

my desired outcome is to be able to print out a scoreboard, in order. Current code for this scoreboard is

print("first place is ", scoreboard[0] ,
      "\nsecond place is ", scoreboard[1], 
      "\nthird place is "  ,scoreboard[2], 
      "\nfourth place is " ,scoreboard[3], 
      "\nfifth place is "  ,scoreboard[4])
3

There are 3 best solutions below

0
On

A way to create a sorted scoreboard for your list. I don't see why you should concatenate your player names and scores though, those should be seperate variables.

n=0
scoreboard = ["player1 37","player3 45","player2 75", "player32 43"]
def myFunc(e):
    return int(e.split(" ")[1])
scoreboard = sorted(scoreboard, key=myFunc, reverse=True)
print("SCOREBOARD:")
for players in scoreboard:
    print("{0}: {1}".format(n+1,scoreboard[n]))
    n+=1
0
On

As others have mentioned, you are probably trying to do this in a very weird way. To answer your question:

myString = "player1 37"
score = int(myString.split(" ").pop())

What happens here: It splits the string into a list, dividing at the space. Pop takes the last element of list, and int() converts it to an integer because having a score as a string is a really bad idea in the first place.

0
On

Instead of

delchars = Player1.join(c for c in map(chr, range(256)) if not c.isalnum())

use

delchars = "".join([c for c in Player1 if not c.isalnum()])