python AttributeError:'NoneType'对象在列表中没有属性'replace'

时间:2018-02-06 12:08:05

标签: python list replace

#@ Row 1, Column 4: Invalid character value for cast specification @#

BCC,01,12697,2013-12- 12,1.0,2014004,CR,ACCOUN TS PAYABLE,-86.23000 ,,,2200-000-000 ,, ,,,, True ,, 0,False ,,, False ,,,,,, 0.00000,0.00000

我正在尝试删除日期值中的选项卡以及每行数据中的其他位置。

columndata = [str(items.replace('\t', '')) for items in list(row)]

但是,此命令会返回以下错误:

  File "apdetfac.py", line 60, in <listcomp>
  columndata = [str(items.replace('\t', '')) for items in list(row)]
  AttributeError: 'NoneType' object has no attribute 'replace'

我尝试将项目转换为str,如下面的列表(行)中的str(items)但产生了另一个错误。怎么办?

2 个答案:

答案 0 :(得分:1)

很难说出你有什么数据,但这给出了正确的答案:

row_str = 'BCC,01,12697,2013-12-\t12,1.0,2014004,CR,ACCOUN\tTS PAYABLE,-86.23000,,2200-000-000,, ,,,,True,,0,False,,,False,,,,,,0.00000,0.00000'
# note the '\t' in date and ACCOUNTS

row = row_str.split(',')

columndata = [str(items.replace('\t', '')) for items in row]

print(columndata)

输出:

['BCC', '01', '12697', '2013-12-12', '1.0', '2014004', 'CR', 'ACCOUNTS PAYABLE', '-86.23000', '', '2200-000-000', '', ' ', '', '', '', 'True', '', '0', 'False', '', '', 'False', '', '', '', '', '', '0.00000', '0.00000']

当然这个列表可以连接成一个字符串:

new_row = ','.join(columndata)
print(new_row)

输出:

BCC,01,12697,2013-12-12,1.0,2014004,CR,ACCOUNTS PAYABLE,-86.23000,,2200-000-000,, ,,,,True,,0,False,,,False,,,,,,0.00000,0.00000

答案 1 :(得分:0)

data = "'BCC,01,12697,2013-12-\t12,1.0,2014004,CR,ACCOUN\tTS PAYABLE,-86.23000,,2200-000-000,, ,,,,True,,0,False,,,False,,,,,,0.00000,0.00000'"

print(','.join(map(lambda x: x.replace('\t',''), data.split(','))))
>>>'BCC,01,12697,2013-12-12,1.0,2014004,CR,ACCOUNTS PAYABLE,-86.23000,,2200-000-000,, ,,,,True,,0,False,,,False,,,,,,0.00000,0.00000'