Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Python, how can I naturally sort a list of alphanumeric strings such that alpha characters sort ahead of numeric characters?
    text
    copied!<p>This is a fun little challenge that confronted me recently. I'll provide my answer below, but I'm curious to see whether there are more elegant or efficient solutions.</p> <p>A delineation of the requirements as they were presented to me:</p> <ol> <li>Strings are alphanumeric (see test dataset below)</li> <li>Strings should be sorted naturally (see <a href="https://stackoverflow.com/q/4836710/1093087">this question</a> for explanation)</li> <li>Alpha characters should be sorted ahead of numeric characters (i.e. 'abc' before '100')</li> <li>Uppercase instances of alpha chars should be sorted ahead of lowercase instances (i.e. 'ABc', 'Abc', 'abc')</li> </ol> <p>Here's a test dataset:</p> <pre><code>test_cases = [ # (unsorted list, sorted list) (list('bca'), ['a', 'b', 'c']), (list('CbA'), ['A', 'b', 'C']), (list('r0B9a'), ['a', 'B', 'r', '0', '9']), (['a2', '1a', '10a', 'a1', 'a100'], ['a1', 'a2', 'a100', '1a', '10a']), (['GAM', 'alp2', 'ALP11', '1', 'alp100', 'alp10', '100', 'alp1', '2'], ['alp1', 'alp2', 'alp10', 'ALP11', 'alp100', 'GAM', '1', '2', '100']), (list('ra0b9A'), ['A', 'a', 'b', 'r', '0', '9']), (['Abc', 'abc', 'ABc'], ['ABc', 'Abc', 'abc']), ] </code></pre> <hr> <p><strong>Bonus Test Case</strong></p> <p>This is inspired by <a href="https://stackoverflow.com/questions/12184015/in-python-how-can-i-naturally-sort-a-list-of-alphanumeric-strings-such-that-alp#comment16314634_12184015">Janne Karila's comment</a> below that the selected answer currently fails (but wouldn't really be a practical concern in my case):</p> <pre><code>(['0A', '00a', 'a', 'A', 'A0', '00A', '0', 'a0', '00', '0a'], ['A', 'a', 'A0', 'a0', '0', '00', '0A', '00A', '0a', '00a']) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload