在Python中打印列表元素和字符串有不同的结果 [英] Printing list elements and strings in Python have different results
问题描述
我有一个 .csv
文件,编码在 UTF-8
。
我使用Python 2.7
。
某些整合发生在 Ubuntu
。
当我打印出这样的文件的结果:
I have a .csv
file which is encoded in UTF-8
.
I am working with Python 2.7
.
Something intereseting happens on Ubuntu
.
When I print out the results of the file like this:
with open("file.csv", "r") as file:
myFile = csv.reader(file, delimiter = ",")
for row in myFile:
print row
我得到 \xc3\x
, \ xa1 \
,....请注意, row
是一个列表,列表中的所有元素都被标记为字符串''
。
当我打印出这样的结果:
I get signs like \xc3\x
, \xa1\
, .... Note that row
is a list and all the elements in my list are marked as strings by ''
in the output.
When I print out the results like this:
with open("file.csv", "r") as file:
myFile = csv.reader(file, delimiter = ",")
for row in myFile:
print ",".join(row)
一切都解码得很好。请注意,我原始文件中的每一行都是一个大字符串。
Everything is decoded fine. Note that every row from my original file is one big string here.
为什么?
推荐答案
这是因为在打印列表的情况下,Python使用 repr()
,但是当打印字符串时,它使用 str()
。示例:
This is because in the case of printing a list, Python is using repr()
, but when printing a string it is using str()
. Example:
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: ['\xc3\xa5\xc3\xa4\xc3\xb6', '\xc3\xa5\xc3\xa4\xc3\xb6']
repr: '\xc3\xa5\xc3\xa4\xc3\xb6'
str: åäö
这篇关于在Python中打印列表元素和字符串有不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!