Welcome, guest | Sign In | My Account | Store | Cart

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, 27 lines
 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) 

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

2 comments

Raymond Hettinger 18 years, 5 months ago  # | flag

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

print "Right order:"
stufflist.sort(key=locale.strxfrm) # using locale
print "".join(stufflist)
Chris Arndt 18 years, 5 months ago  # | flag

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.

Created by Eino Mäkitalo on Sat, 29 Oct 2005 (PSF)
Python recipes (4591)
Eino Mäkitalo's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks