[newbie] problem with data (different behaviour between batch and interactive use)

Jussi Piitulainen jpiitula at ling.helsinki.fi
Wed Jun 27 08:46:39 EDT 2012


Jean Dupont writes:

> If I start python interactively I can separate the fields as
> follows:
> >measurement=+3.874693E01,+9.999889E03,+9.910000E+37,+1.876[...]
> >print measurement[0]
> 0.3874693
[...]
> The script does this:
> measurement=serkeith.readline().replace('\x11','').replace([...]
> print measurement[0]
> +
[...]
> can anyone here tell me what I'm doing wrong and how to do it
> correctly

When you index a string, you get characters. Your script handles a
line as a string. Interact with Python using a string for your data to
learn how it behaves and what to do: split the string into a list of
written forms of the numbers as strings, then convert that into a list
of those numbers, and index the list.

This way:

>>> measurement = "+3.874693E01,+9.999889E03,+9.910000E+37"
>>> measurement
'+3.874693E01,+9.999889E03,+9.910000E+37'
>>> measurement.split(',')
['+3.874693E01', '+9.999889E03', '+9.910000E+37']
>>> measurement.split(',')[0]
'+3.874693E01'
>>> float(measurement.split(',')[0])
38.746929999999999
>>> map(float, measurement.split(','))
[38.746929999999999, 9999.8889999999992, 9.9100000000000005e+37]
>>> map(float, measurement.split(','))[0]
38.746929999999999
>>> 

In your previous interactive session you created a tuple of numbers,
which is as good as a list in this context. The comma does that,
parentheses not required:

>>> measurement = +3.874693E01,+9.999889E03,+9.910000E+37
>>> measurement
(38.746929999999999, 9999.8889999999992, 9.9100000000000005e+37)



More information about the Python-list mailing list