python list转换字符串报错 TypeError: sequence item 4: expected str instance, float found

背景:

python3.8

在使用模块xlrd读取excel表数据时,把从excel表中每一行数据用字符串拼接时,遇到错误如下:

TypeError: sequence item 4: expected str instance, float found

根据报错提示,找到问题所在使用xlrd提取excel中每一行数据时,数字被自动转成成整数/浮点数。如:

['A', 'AA', '', '', 2.0, '', 1]
['B', 'BB', '', '', 2.0, '', 1]
['C', 'CC', '', '', 2.0, '', 1]

解决方法:

li=['A', 'AA', '', '', 2.0, '', 1]


print('##'.join(str(i) for i in li))
print('##'.join([str(i) for i in li]))

# 建议使用map 更加节省时间
print('##'.join(map(str,li)))

原因:

$ python -m timeit '"-".join(str(n) for n in range(1000))'
1000 loops, best of 3: 219 usec per loop

$ python -m timeit '"-".join(str(n) for n in range(1000))'
1000 loops, best of 3: 216 usec per loop

$ python -m timeit '"-".join(map(str, range(1000)))'
10000 loops, best of 3: 113 usec per loo

从上述可以得知:使用map是最节省时间。

注意:上述命令无法直接在window中执行,会提示错误:SyntaxError: EOL while scanning string literal。具体原因未知。

原文网址:http://www.chenxm.cc/article/1057.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值