Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split this string up?

Tags:

python

io

...    
    1947q2        -0.6
    1947q3        -0.3
    1947q4         6.2
    1948q1        16.5
...

How do I get this text file into a list? I'm having problems with the spacing between the year and corresponding values.

This is what I have so far:

data = []

for line in open("file"):
    if '1947' in line:
        sl = line.split('       ')
        data.append((sl[0], sl[1]))

print data
like image 365
super9 Avatar asked Mar 22 '26 20:03

super9


2 Answers

Just using split() without arguments splits by whitespace, and eats consecutive whitespace:

>>> s='    1947q2        -0.6'
>>> s.split()
['1947q2', '-0.6']
like image 153
Thomas Avatar answered Mar 25 '26 09:03

Thomas


data = []

with open("file") as fin:
    for line in fin:
        data.append(tuple(line.split()))

print data
like image 27
gorlum0 Avatar answered Mar 25 '26 10:03

gorlum0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!