Search code examples
pythonstringsortingalphabetical-sort

python sort strings with leading numbers alphabetically


I have a list of filenames, each of them beginning with a leading number:

10_file
11_file
1_file
20_file
21_file
2_file ...

I need to put it in this order:

1_file
10_file
11_file
2_file
21_file
22_file ...

If they were just numbers as strings ('1') without the underscore I could sort them with sorted(). I have tried different sort-methods with different key-attributes, also the module "natsort", but with no result. Do I have to write my own algorithm for this? Maybe I could extract the leading numbers and use them for sorting?

UPDATED desired list to correct listing


Solution

  • Sorting, splitting and list comprehensions work well here.

    lst = ['10_file', '11_file', '1_file', '20_file', '21_file', '2_file']
    
    lst_split = ['_'.join(x) for x in sorted(i.split('_') for i in lst)]
    
    # ['1_file', '10_file', '11_file', '2_file', '20_file', '21_file']