Library function for sorting

Paul Winkler slinkp23 at
Wed Oct 17 06:24:25 CEST 2001

On 17 Oct 2001 02:06:33 GMT, Michael Yuen <myuen at> wrote:
>I'm really new to this Python stuff and was wondering if there's a 
>library function for sorting strings.  I sure there is one but haven't 
>been able to find one when I looked through the documentation.

The usual way is to put them in a list and use the list's sort()
method.  By default, this sorts in ASCII order - e.g. capitals in
alphabetical order, then lowercase in alphabetical order.  Example:

>>> words = ['foo', 'bar', 'Baz', 'bat', 'baf', 'spam', 'eggs', 'bacon']
>>> words.sort()
>>> words
['Baz', 'bacon', 'baf', 'bar', 'bat', 'eggs', 'foo', 'spam']

See the standard library reference, section, for more on list

If you want to sort by some other algorithm, pass in a comparison
function. The comparison function should return 1, 0, or -1, as
described in the reference above. The list will be put in *ascending*
order according to this function. Example: Let's sort a list of
strings by the last character in each string, ignoring the case.

>>> def cmp_last_nocase(a, b):
...     aLast = a[-1].upper() # force all to uppercase
...     bLast = b[-1].upper() # for purposes of comparison
...     if aLast > bLast: return 1
...     elif aLast == bLast: return 0
...     else: return -1
>>> words.sort(cmp_last_nocase) # pass the function - don't call it!
>>> words
['baf', 'spam', 'bacon', 'foo', 'bar', 'eggs', 'bat', 'Baz']

Hope that helps...


More information about the Python-list mailing list