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
Faster to use key=locale.strxfrm than cmp=locale.strcoll.
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