As plain strings, "img10" sorts before "img9", which annoys everyone. Write natural_sort(names: list[str]) -> list[str] that returns a new list in natural order:
- Split names into chunks: maximal runs of digits and of non-digits (
"Roll2_img10.jpg"is"Roll","2","_img","10",".jpg"). - Compare chunk by chunk: digit chunks by numeric value (
"007"equals"7"), text chunks case-insensitively, and a digit chunk sorts before a text chunk. - If one name runs out first, it comes first. Still tied? Compare the whole names as plain strings.
natural_sort(["img10.jpg", "img9.jpg", "IMG2.jpg", "img2.JPG"])
# ["IMG2.jpg", "img2.JPG", "img9.jpg", "img10.jpg"]
natural_sort(["a7", "a07", "a", "7a"])
# ["7a", "a", "a07", "a7"]
Up to 10^5 names of 0 to 30 printable ASCII characters; don't change the input.
⭐ Bonus: a speed test with 20,000 names earns a star if you compute one key per name and sort once.
Show hint
re.findall(r"\d+|\D+", name) gives the chunks. Make each a same-shaped tuple, (0, int(c), "") or (1, 0, c.lower()), and sort by (chunk_tuples, name).