pythonstringsorting

Custom sorting a single string


I have a list of five-character strings, each string representing a hand of five playing cards. I want to sort each string so it's in ascending order by number, followed by the cards (T,J,Q,K,A). So “Q4JTK”, "9T43A" and “T523Q” will sort to “4TJQK”, "349TA" and “235TQ” respectively. I can sort a numeric five character string using:

def sort_string(s): 
return ''.join(sorted(s))

print(sort_string("21437"))

But how to sort a string with numbers and letters? I would probably find a regular function easier to follow than a lambda function. Thanks.


Solution

  • Sorting by index in the desired order:

    def sort_string(s): 
        return ''.join(sorted(s, key='23456789TJQKA'.index))
    
    print(sort_string('Q4JTK') == '4TJQK')
    print(sort_string('9T43A') == '349TA')
    print(sort_string('T523Q') == '235TQ')
    

    Attempt This Online!