Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to zfill after a certain value in a list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 _ ?

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading