Python Unicode to String conversion

iapain iapain at gmail.com
Sat Sep 1 03:17:14 EDT 2007


First make sure your DB encoding is UTF-8 not the latin1

> The error I keep having is something like this:
> ERREUR:  Séquence d'octets invalide pour le codage «UTF8» : 0xe02063

then try this:

def smart_str(s, encoding='utf-8', errors='strict'):
    """
    Returns a bytestring version of 's', encoded as specified in
'encoding'.
    """
    if not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            return unicode(s).encode(encoding, errors)
    elif isinstance(s, unicode):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s






More information about the Python-list mailing list