背景:
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。具体原因未知。