我在变量中存储了以下Unicode文本:
myvariable = 'Gen\xe8ve'
我想要做的是打印myvariable
并显示:
Genève
我尝试了但失败了:
print myvariable.decode('utf-8')
做正确的方法是什么?最后,我想将字符串打印到文本文件中。 我使用的是Python 2.7。
更新 还试过这个:
In [23]: myvariable = u'Gen\xe8ve'
In [24]: print myvariable
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-24-1eb59a50889d> in <module>()
----> 1 print myvariable
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 3: ordinal not in range(128)
更新2 :
我真的想从myvariable
打印。实际代码Gen\xe8ve
是从xml.etree.ElemTree解析器中提取的,如:
myvariable = actress.find('name').text
## The following doesn't work.
# print u'myvariable'
答案 0 :(得分:1)
那不是Unicode文本,这是一个字节串。 此是Unicode文本:
myvariable = u'Gen\xe8ve'
print myvariable
答案 1 :(得分:1)
直接打印unicode字符串时
myvariable = u'Gen\xe8ve'
print myvariable
python尝试使用默认编码(sys.stdout.encoding
)对其进行编码。由于它在您的系统上似乎是ascii
,它会尝试ascii并失败(在ascii中没有\xe8
这样的东西)。尝试明确指定编码:
myvariable = u'Gen\xe8ve'
print myvariable.encode('utf-8')
答案 2 :(得分:0)
'\xe8'
不是UTF8,它是其他一些编码。
尝试:
>>> x = 'Gen\xc3\xa8ve'
>>> print x.decode('utf8')
或者找出实际编码是什么,然后解码。