下打印显示了我的预期值。
(sys.stdout.encoding和sys.stdin.encoding都是'UTF-8')。
为什么变量值与其打印值不同?我需要将原始值变成一个变量。
>>username = 'Jo\xc3\xa3o'
>>username.decode('utf-8').encode('latin-1')
'Jo\xe3o'
>>print username.decode('utf-8').encode('latin-1')
João
原题:
我有一个问题,查询BD和值解码成Python。
我证实了我的DB NLS_LANG使用
select property_value from database_properties where property_name='NLS_CHARACTERSET';
'''AL32UTF8 stores characters beyond U+FFFF as four bytes (exactly as Unicode defines
UTF-8). Oracle’s “UTF8” stores these characters as a sequence of two UTF-16 surrogate
characters encoded using UTF-8 (or six bytes per character)'''
os.environ["NLS_LANG"] = ".AL32UTF8"
....
conn_data = str('%s/%[email protected]%s') % (db_usr, db_pwd, db_sid)
sql = "select user_name apex.users where user_id = '%s'" % userid
...
cursor.execute(sql)
ldap_username = cursor.fetchone()
...
其中
print ldap_username
>>'Jo\xc3\xa3o'
我用尽全力(返回相同)
ldap_username.decode('utf-8')
>>u'Jo\xe3o'
unicode(ldap_username, 'utf-8')
>>u'Jo\xe3o'
其中
u'João'.encode('utf-8')
>>'Jo\xc3\xa3o'
如何将查询结果返回给适当的“João”?
谢谢jro。尽管我在第二和第三个例子中得到了完全相同的结果,但在您的第一个例子中,我会得到:João,而不是João。 如何获取存储在数据库中的原始值“João”到Python对象中? –
@JoaoFigueiredo:我更新了答案以解决您的其他问题。 – jro
如果我不清楚,我很抱歉。我认为我掌握了解码和编码的基本原理(u'string'不会对其类型产生任何疑问)。我的问题仍然是如何将原始字符串传递给外部API。 –