Skip to content Skip to sidebar Skip to footer

Python Sort Strings Started With Digits

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','Ano

Solution 1:

Here's a function that works for the general case

import re
defnatkey(s):
    return [int(p) if p else q for p, q in re.findall(r'(\d+)|(\D+)', s)]

x = ['1th Word', 'Another Word 2x', 'Another Word 20x', '10th Word 10', '2nd Word']

printsorted(x)
printsorted(x, key=natkey)

Result:

['10th Word 10', '1th Word', '2nd Word', 'Another Word 20x', 'Another Word 2x']['1th Word', '2nd Word', '10th Word 10', 'Another Word 2x', 'Another Word 20x']

Solution 2:

Solution 3:

r = re.compile(r'(\d+)')
defsort_by_number(s):
    m = r.match(s)
    return m and m.group(0) or s

x.sort(key=sort_by_number)

Key is that if there was not match, return the string as is

Post a Comment for "Python Sort Strings Started With Digits"