Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort unicode strings alphabetically in Python?

Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?

Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.

If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?

like image 543
Lennart Regebro Avatar asked Jul 08 '09 12:07

Lennart Regebro


People also ask

Can you sort a string alphabetically in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do you sort letters alphabetically in Python?

Use sorted() and str. join() to sort a string alphabetically in Python. Another alternative is to use reduce() method. It applies a join function on the sorted list using the '+' operator.

How do you sort a string alphabetically in Python without sorting?

You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.


1 Answers

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'] 
like image 164
Rafał Dowgird Avatar answered Sep 20 '22 21:09

Rafał Dowgird