Have a look at the following string:
E|1256280||2014-01-05 17:54:00|1|2014-01-05 18:59:53|True
I'd like to split it wrt. the pipe symbol "|". Therefore I use the following python code (where line is a string containing the described string above):
print line
print str(type(line))
print str(line[1])
parts = line.split['|']
print str(parts)
However, when using this piece of code i get the following error:
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
However, I don't understand what I am doing wrong here. Any suggestions?
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.
The Python split() method divides a string into a list. Values in the resultant list are separated based on a separator character. The separator is a whitespace by default.
Python has a built-in method you can apply to string, called . split() , which allows you to split a string by a certain delimiter.
The
parts = line.split['|']
should be
parts = line.split('|')
(i.e. with parentheses instead of square brackets.)
To call a method, use ()
around the arguments:
parts = line.split('|')
not []
, which is the syntax for sequence indexing.
I'd use the csv
module instead, configuring the reader with the |
character as the delimiter:
import csv
with open(filename, 'rb') as infh:
reader = csv.reader(infh, delimiter='|')
for row in reader:
print row
will handle splitting for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With