ActiveState Code

Recipe 442492: Using sorting order of your country/culture when sorting (collate,locale)


It takes me over half an hour to learn how it works. (I hope to save your time)

You have to remember to add compare function to your sort/sorted command.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# -*- coding:iso8859-1 -*-
import locale

# using your default locale (user settings)
locale.setlocale(locale.LC_ALL,"")
#locale.setlocale(locale.LC_ALL,"fi") or something else

stuff="aåbäcÖöAÄÅBCabcÅÄÖabcÅÄÖ"

# using sorted-function
print "Wrong order:"
print "".join(sorted(stuff))  # not using locale

print "Right order:"
print "".join(sorted(stuff,cmp=locale.strcoll)) # using locale


# in place sorting
stufflist=list(stuff)

print "Wrong order:"
stufflist.sort()  # not using locale
print "".join(stufflist)  

print "Right order:"
stufflist.sort(cmp=locale.strcoll) # using locale
print "".join(stufflist) 

Discussion

This is quite simple recipe following exactly python's locale manual. See: http://www.python.org/doc/current/lib/module-locale.html

Comments

  1. 1. At 12:49 a.m. on 30 oct 2005, Raymond Hettinger said:

    Faster to use key=locale.strxfrm than cmp=locale.strcoll.

    print "Right order:"
    stufflist.sort(key=locale.strxfrm) # using locale
    print "".join(stufflist)
    
  2. 2. At 3:23 a.m. on 15 nov 2005, Chris Arndt said:

    Compability. Beware:

    • The built-in function 'sorted()' is only available from Python 2.4.

    • Support for the keyword argument 'key' to the 'sort()' method of lists was only added in Python 2.4 as well.

Sign in to comment