#!/usr/bin/env python # coding: UTF-8 import codecs import sys import locale def getTerminalCharset(): """Guess terminal charset using differents tests From http://www.haypocalc.com/wiki/Python_Unicode """ # (1) Try locale.getpreferredencoding() try: charset = locale.getpreferredencoding() if charset: return charset except (locale.Error, AttributeError): pass # (2) Try locale.nl_langinfo(CODESET) try: charset = locale.nl_langinfo(locale.CODESET) if charset: return charset except (locale.Error, AttributeError): pass # (3) Try sys.stdout.encoding if hasattr(sys.stdout, "encoding") and sys.stdout.encoding: return sys.stdout.encoding # (4) Otherwise, returns "ASCII" return "ASCII" charset = getTerminalCharset() print("Encodage de la console : %s" % charset) # Ici l'encodage de la chaine n'est pas connu de python, c'est celui du fichier str_string = "Benoît" # Là Python utilise l'information "coding" en deuxième ligne du fichier # et transforme la chaine en unicode ; la différence et le petit "u" unicode_string = u"Benoît" # Essayons d'afficher les deux string ensemble : # * soit dans une chaine de type str try: print("%s ; %s" % (str_string, unicode_string)) except UnicodeDecodeError as error: print(error) # * soit dans une chaine de type unicode try: print(u"%s ; %s" % (str_string, unicode_string)) except UnicodeDecodeError as error: print(error) # Même problème dans les deux cas, on mélange str et unicode # Python essaye de convertir implicitement, mais ne peut pas deviner l'encodage # de str_string et essaye avec ASCII ... échec. # Deux solutions : # * convertir d'abord unicode_string dans l'encodage de la console print("%s ; %s" % (str_string, unicode_string.encode(charset))) # * convertir d'abord str_string en unicode ; dans ce cas, l'ensemble de la # chaîne sera à nouveau convertis implicitement dans l'encodage de la console # pour affichage print(u"%s ; %s" % (str_string.decode(charset), unicode_string)) # Résumé print('Type : %s ; repr : %s ; valeur : %s' % ( type(str_string), repr(str_string), str_string)) print(u'Type : %s ; repr : %s ; valeur : %s' % ( unicode(repr(type(unicode_string))), unicode(repr(unicode_string)), unicode_string))