看一下以下字符串:
E|1256280||2014-01-05 17:54:00|1|2014-01-05 18:59:53|True
我想把它分开。管道符号“|”。因此,我使用以下python代码(其中line是包含上述字符串的字符串):
print line
print str(type(line))
print str(line[1])
parts = line.split['|']
print str(parts)
然而,当使用这段代码时,我收到以下错误:
E|1256280||2014-01-05 17:54:00|1|2014-01-05 18:59:53|True
<type 'str'>
|
Traceback (most recent call last):
File "/path/to/my/pythonscritp.py", line 34, in crawl_live_quotes
parts = line.split['|']
TypeError: 'builtin_function_or_method' object is not subscriptable
然而,我不明白我在这里做错了什么。有什么建议吗?
答案 0 :(得分:13)
在
parts = line.split['|']
应该是
parts = line.split('|')
(即用括号代替方括号。)
答案 1 :(得分:2)
要调用方法,请在参数周围使用()
:
parts = line.split('|')
不是[]
,这是序列索引的语法。
我会使用csv
module代替,使用|
字符作为分隔符配置阅读器:
import csv
with open(filename, 'rb') as infh:
reader = csv.reader(infh, delimiter='|')
for row in reader:
print row
会处理拆分。