F. Boudin F. Boudin - 1 year ago 80
Python Question

Python string.letters does not include locale diacritics

I am trying to get the alphabet from python string module depending on a given locale with no success (that is with the diacritics, i.e. éèêà... for French). Here is a minimal example :

import locale, string

locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
print string.letters
# shows ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
print string.letters
# also shows ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

In the python documentation, it is said that string.letters is locale dependent, but it seems that it does not work for me.

What I am doing wrong and is it the right way to obtain a language-dependent alphabet ?

Edit: I just checked the locale
print locale.getlocale()
after setting and it is correctly changed.

Answer Source

In python 2.7 (there is no string.letters in python 3.x) it works if you set the locale to 'fr_FR' (equivalent to 'fr_FR.ISO8859-1', not 'fr_FR.UTF-8').

>>> import locale, string
>>> locale.setlocale(locale.LC_ALL, 'es_ES')
>>> string.letters
>>> locale.setlocale(locale.LC_ALL, 'es_ES.UTF-8')
>>> string.letters

So \xaa is character "ª", \xab "«", \xd1 is "Ñ" and so on. But the encoding representation is indeed broken.

I do highly recommended reading this website: https://pythonhosted.org/kitchen/unicode-frustrations.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download