Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python : Split string separated by a pipe symbol "|"

Tags:

python

split

pipe

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?

like image 685
toom Avatar asked Jan 05 '14 18:01

toom


People also ask

How do you split a string separated in Python?

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.

How do you split a symbol in Python?

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.

What .split means in Python?

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.

Can I split a string by two delimiters Python?

Python has a built-in method you can apply to string, called . split() , which allows you to split a string by a certain delimiter.


2 Answers

The

parts = line.split['|']

should be

parts = line.split('|')

(i.e. with parentheses instead of square brackets.)

like image 80
NPE Avatar answered Oct 02 '22 21:10

NPE


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.

like image 42
Martijn Pieters Avatar answered Oct 02 '22 19:10

Martijn Pieters