在 Python 中打印列表元素和字符串有不同的结果



我有一个用UTF-8编码的.csv文件。我正在使用Python 2.7Ubuntu上发生了一些令人不安的事情.当我像这样打印出文件的结果时:

with open("file.csv", "r") as file:
    myFile = csv.reader(file, delimiter = ",")
    for row in myFile:
        print row

我得到像xc3xxa1、....请注意,row是一个列表,列表中的所有元素都通过输出中的''标记为字符串。当我打印出这样的结果时:

with open("file.csv", "r") as file:
    myFile = csv.reader(file, delimiter = ",")
    for row in myFile:
        print ",".join(row)

一切都解码得很好。请注意,我的原始文件中的每一行在这里都是一个大字符串。

为什么?

这是因为在打印列表的情况下,Python 使用的是 repr() ,但在打印字符串时,它使用的是 str() 。 例:

unicode_str = 'åäö'
unicode_str_list = [unicode_str, unicode_str]
print 'unwrapped:', unicode_str
print 'in list:', unicode_str_list
print 'repr:', repr(unicode_str)
print 'str:', str(unicode_str)

生产:

unwrapped: åäö
in list: ['xc3xa5xc3xa4xc3xb6', 'xc3xa5xc3xa4xc3xb6']
repr: 'xc3xa5xc3xa4xc3xb6'
str: åäö

最新更新