2

I have a list with entry like that:

["foo1bar","foo2bar", ..., "foo10bar", "foo11bar", ..., "foo100bar", ...]

foo is fixed for the set of data (but could vary between the sets), and bar can vary even in the same set of data. If I use sort, the list is badly sorted (1, 10, 100, 2, etc.). How can I sort it correctyly? With a regex extractig the numeral part of the strings?

Shan-x
  • 1,146
  • 6
  • 19
  • 44
  • You should probably use `natsort` as in the accepted answer for [this question](http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) if you don't mind using a library. – Aaron Christiansen Jun 30 '16 at 09:36
  • I prefer implement it rather than use a third part library. – Shan-x Jun 30 '16 at 09:38
  • In that case, look at some of the further-down answers of the question which use regex. – Aaron Christiansen Jun 30 '16 at 09:38
  • list_ = ["foo1bar","foo2bar", "foo10bar", "foo11bar", "foo100bar",] regex = re.compile('foo(\d+)bar') try: sorted(a, key=lambda x: regex.match(x).group(1)) except IndexError: print('Invalid pattern') – Devi Prasad Khatua Jun 30 '16 at 09:41

0 Answers0