Python 无法以字符串形式保存utf-8编码的内容

Python 无法以字符串形式保存utf-8编码的内容,python,string,unicode,utf-8,python-2.7,Python,String,Unicode,Utf 8,Python 2.7,我正在查询Twitter API并收到utf-8编码的答案。现在我想用format()函数将这些答案保存在字符串中。这就是我到目前为止所做的(我已经尝试了很多选择) 当tName/tLocation包含诸如\xe4之类的内容时,str(tName)、str(tLocation)等会给我错误 ERROR:__main__:'ascii' codec can't encode character u'\xe4' in position 10: ordinal not in range(128) Tr

我正在查询Twitter API并收到utf-8编码的答案。现在我想用
format()
函数将这些答案保存在字符串中。这就是我到目前为止所做的(我已经尝试了很多选择)

当tName/tLocation包含诸如\xe4之类的内容时,str(tName)、str(tLocation)等会给我错误

ERROR:__main__:'ascii' codec can't encode character u'\xe4' in position 10: ordinal not in range(128)
Traceback (most recent call last):
  File "../code/userinfo_extraction_old.py", line 167, in <module>
    outputList = [str(tName),
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 10: ordinal not in range(128)
错误:_main__:'ascii'编解码器无法对位置10中的字符u'\xe4'进行编码:序号不在范围内(128)
回溯(最近一次呼叫最后一次):
文件“./code/userinfo\u extraction\u old.py”,第167行,在
outputList=[str(tName),
UnicodeEncodeError:“ascii”编解码器无法对位置10中的字符u'\xe4'进行编码:序号不在范围内(128)

我试图理解它是如何工作的,但我无法找出这里的错误。我还尝试使用unicode()而不是str()…没有机会。

要将
unicode
数据转换为
str
,需要指定编码。使用
tName.encode('utf8')

您可能想了解Python和Unicode:

  • 内德·巴奇尔德

  • 乔尔斯波尔斯基


…您正在运行Python 2。什么?是的,Python 2.7,忘了提到这一点,抱歉。请尝试str=str.decode('utf-8')您的意思是我应该把它放在所有str调用之上,这意味着覆盖默认str函数?或者执行类似于
str(tName.decode('utf-8')的操作
?非常感谢。是的,我以前可能读过一两篇这样的文档,但是因为这个主题太无聊了,我总是在一周后忘记一半的内容……不过还是要感谢链接。
ERROR:__main__:'ascii' codec can't encode character u'\xe4' in position 10: ordinal not in range(128)
Traceback (most recent call last):
  File "../code/userinfo_extraction_old.py", line 167, in <module>
    outputList = [str(tName),
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 10: ordinal not in range(128)