How do I sort unicode strings alphabetically in Python? How do I sort unicode strings alphabetically in Python? python python

How do I sort unicode strings alphabetically in Python?


IBM's ICU library does that (and a lot more). It has Python bindings: PyICU.

Update: The core difference in sorting between ICU and locale.strcoll is that ICU uses the full Unicode Collation Algorithm while strcoll uses ISO 14651.

The differences between those two algorithms are briefly summarized here: http://unicode.org/faq/collation.html#13. These are rather exotic special cases, which should rarely matter in practice.

>>> import icu # pip install PyICU>>> sorted(['a','b','c','ä'])['a', 'b', 'c', 'ä']>>> collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8'))>>> sorted(['a','b','c','ä'], key=collator.getSortKey)['a', 'ä', 'b', 'c']


I don't see this in the answers. My Application sorts according to the locale using python's standard library. It is pretty easy.

# python2.5 code below# corpus is our unicode() strings collection as a listcorpus = [u"Art", u"Älg", u"Ved", u"Wasa"]import locale# this reads the environment and inits the right localelocale.setlocale(locale.LC_ALL, "")# alternatively, (but it's bad to hardcode)# locale.setlocale(locale.LC_ALL, "sv_SE.UTF-8")corpus.sort(cmp=locale.strcoll)# in python2.x, locale.strxfrm is broken and does not work for unicode strings# in python3.x however:# corpus.sort(key=locale.strxfrm)

Question to Lennart and other answerers: Doesn't anyone know 'locale' or is it not up to this task?


Try James Tauber's Python Unicode Collation Algorithm. It may not do exactly as you want, but seems well worth a look. For a bit more information about the issues, see this post by Christopher Lenz.