I would like to know how can I sort a string by the number inside.
As example I have:
hello = " hola %d" % (number_from_database)
bye = "adios %d" % (number_from_database_again)
I want to sort them by the number even if it changes.
I would like to know how can I sort a string by the number inside.
As example I have:
hello = " hola %d" % (number_from_database)
bye = "adios %d" % (number_from_database_again)
I want to sort them by the number even if it changes.
You can pass a key to sort:
sorted(l, key=lambda x: int(re.sub('\D', '', x)))
For example:
In [1]: import re
In [2]: l = ['asdas2', 'asdas1', 'asds3ssd']
In [3]: sorted(l, key=lambda x: int(re.sub('\D', '', x)))
Out[3]: ['asdas1', 'asdas2', 'asds3ssd']
Where re.sub('\D', '', x)
replaces everything but the digits.
Just a little complement to Andy's answer.
If you want to sort set which also contain strings without any number:
sorted(l, key=lambda x: int('0'+re.sub('\D', '', x)))
, which would put those strings without any number at the very beginning.
The solutions above do not work for strings with the format:
test 8 - test 18
The following code will return 818
instead of 8
:
x = 'test 8 - test 18'
res = int(re.sub(r'\D', '', x))
print(res)
>>> 818
The solution for this is doing a search
and getting the group
result:
x = 'test 8 - test 18'
res = int(re.search(r'\d+', x).group())
print(res)
>>> 8
So, the final solution with this correction is:
l = [
'test 9 - test 8',
'test 8 - test 18'
]
l2 = sorted(l, key=lambda x: int(re.search(r'\d+', x).group()))
print(l)
print(l2)
>>> ['test 9 - test 8', 'test 8 - test 18']
['test 8 - test 18', 'test 9 - test 8']
salutations = [hello, bye]
salutations.sort(key=lambda x: int(filter(lambda s: s.isdigit(), x.split())[0]))