Home > Net >  How to zfill after a certain value in a list
How to zfill after a certain value in a list

Time:11-25

I have a list that looks like this

ls =
['DATA2022_10.csv',
 'DATA2022_2.csv',
 'DATA2022_3.csv',
 'DATA2022_4.csv',
 'DATA2022_5.csv',
 'DATA2022_6.csv',
 'DATA2022_7.csv',
 'DATA2022_8.csv',
 'DATA2022_9.csv']

I want to zfill element in this list in order to sort my data.

Expected output:

ls =
['DATA2022_02.csv',
 'DATA2022_03.csv',
 'DATA2022_04.csv',
 'DATA2022_05.csv',
 'DATA2022_06.csv',
 'DATA2022_07.csv',
 'DATA2022_08.csv',
 'DATA2022_09.csv',
 'DATA2022_10.csv']

zfill only allows me to add 0 on the left or on the right, How can I add the 0 only after the 9th value of the element of my list, i.e. the _ ?

CodePudding user response:

You don't even need to add zero and sort. If your goal is to sort the list use natsort directly.

from natsort import natsorted

new =natsorted(ls)
print(new)

Gives #

['DATA2022_2.csv', 'DATA2022_3.csv', 'DATA2022_4.csv', 'DATA2022_5.csv', 'DATA2022_6.csv', 'DATA2022_7.csv', 'DATA2022_8.csv', 'DATA2022_9.csv', 'DATA2022_10.csv']
  • Related