Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort string by number inside

Tags:

python

string

int

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.

like image 347
Victor Castillo Torres Avatar asked Jun 05 '13 17:06

Victor Castillo Torres


People also ask

How do you sort a string with a number inside in Python?

To do this we can use the extra parameter that sort() uses. This is a function that is called to calculate the key from the entry in the list. We use regex to extract the number from the string and sort on both text and number.

How do you sort numerically in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.

How do you sort a number in an array of strings?

sort() Method. In Java, Arrays is the class defined in the java. util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting.


2 Answers

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.

like image 140
Andy Hayden Avatar answered Nov 08 '22 19:11

Andy Hayden


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.

like image 27
Yuan Tao Avatar answered Nov 08 '22 18:11

Yuan Tao