2

I was wondering if there is a cleaner way to parse the following string:

line = "NOVEL_SERIES, 3256432, 8, 1, 2.364, 4.5404, 9.8341"
key, id, xval, yval, est1, est2, est3 = line.split()
id   = int(id)
xval = int(value1)
yval = int(value2)
est1 = float(est1)
est2 = float(est2)
est3 = float(est3)
3
  • what is your goal exactly? Commented Feb 26, 2016 at 16:31
  • I think you mean line.split(", ") ? Commented Feb 26, 2016 at 16:32
  • Also you probably mean xval = int(xval) and yval = int(yval) Commented Feb 26, 2016 at 16:34

3 Answers 3

6

Perhaps a bit more readable by expliciting converters :

In [29]: types=[str,int,int,int,float,float]

In [30]: [f(x) for (f,x) in zip(types,line.split(', '))]
Out[30]: ['NOVEL_SERIES', 3256432, 8, 1, 2.364, 4.5404]
Sign up to request clarification or add additional context in comments.

4 Comments

Wow...that's a really interesting approach. Good job!
I have a question, since I am new to Python and just try to understand: why both x('10.9') and float('10.9') return the same value? >>> x <type 'float'> >>> x('10.9') 10.9 >>> float(10.9) 10.9
I don't understand whats is x here ?
B.M. please see the better format question I just added bellow
5

You can use numpy.genfromtxt() to automatically detect data types (inspired by this answer) - specify the dtype as None and set the appropriate delimiter:

>>> import numpy as np
>>> from StringIO import StringIO
>>>
>>> buffer = StringIO(line)
>>> key, id, xval, yval, est1, est2, est3 = np.genfromtxt(buffer, dtype=None, delimiter=", ").tolist()
>>> key
'NOVEL_SERIES'
>>> id
3256432
>>> xval
8
>>> yval
1
>>> est1
2.364
>>> est2
4.5404
>>> est3
9.8341

1 Comment

@idjaw definitely, same here, but we should always remember that "explicit is better than implicit" too.
0

you can build on B.M. s answer to get ALL the fields and name them:

line = "NOVEL_SERIES, 3256432, 8, 1, 2.364, 4.5404, 9.8341"
types=[str,int,int,int,float,float,float]
key, id, xval, yval, est1, est2, est3 = [f(x) for (f,x) in zip(types,line.split(', '))]

>>> [key, id, xval, yval, est1, est2, est3]
['NOVEL_SERIES', 3256432, 8, 1, 2.364, 4.5404, 9.8341]
>>> key
'NOVEL_SERIES'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.