Python sort strings started with digits

Posted by vlad on Stack Overflow See other posts from Stack Overflow or by vlad
Published on 2012-06-02T22:03:21Z Indexed on 2012/06/02 22:40 UTC
Read the original article Hit count: 158

Filed under:

I have the next list:

a = ['1th Word', 'Another Word', '10th Word']
print a.sort()
>>> ['10th Word', '1th Word', 'Another Word']

But I need:

['1th Word', '10th Word','Another Word']

Is there an easy way to do this?

I tried:

r = re.compile(r'(\d+)')
def sort_by_number(s):
    m = r.match(s)
    return m.group(0)

x.sort(key=sort_by_number)

But some strings do not have numbers and this leads to an errors. Thanks.

© Stack Overflow or respective owner

Related posts about python