python打印输出不在列表中的元素_在Python中打印列表元素和字符串有不同的结果...

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

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.

Why is that?

解决方案

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)

Produces:

unwrapped: åäö

in list: ['\xc3\xa5\xc3\xa4\xc3\xb6', '\xc3\xa5\xc3\xa4\xc3\xb6']

repr: '\xc3\xa5\xc3\xa4\xc3\xb6'

str: åäö

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值