views:

166

answers:

3

I would like to know if there is something similar to PHP natsort function in python?

l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'iamge3.jpg']
l.sort()

gives:

['image1.jpg', 'image12.jpg', 'image15.jpg', 'iamge3.jpg']

but I would like to get:

['image1.jpg', 'iamge3.jpg', 'image12.jpg', 'image15.jpg']

UPDATE

Solution base on this link

    def try_int(s):
        "Convert to integer if possible."
        try: return int(s)
        except: return s

    def natsort_key(s):
        "Used internally to get a tuple by which s is sorted."
        import re
        return map(try_int, re.findall(r'(\d+|\D+)', s))

    def natcmp(a, b):
        "Natural string comparison, case sensitive."
        return cmp(natsort_key(a), natsort_key(b))

    def natcasecmp(a, b):
        "Natural string comparison, ignores case."
        return natcmp(a.lower(), b.lower())

    l.sort(natcasecmp);
+2  A: 

Not builtin, an not in the standard library AFAIK. There's a recipe for it here, and other implementations can be found by Google.

Eli Bendersky
Thanks, this will do
Silver Light
+2  A: 

You can check this link: Compact python human sort

sankoz
+2  A: 

From my answer to Natural Sorting algorithm:

import re
def natural_key(string_):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]

Example:

>>> L = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'iamge3.jpg']
>>> L.sort(key=natural_key)
>>> L
['iamge3.jpg', 'image1.jpg', 'image12.jpg', 'image15.jpg']
>>> L[0] = 'image3.jpg'
>>> L.sort(key=natural_key)
>>> L
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
J.F. Sebastian