Reading a comma delimited file
Skip Montanaro
montanaro at tttech.com
Thu Nov 8 13:18:05 EST 2001
Kristen> Does the %f work just like in C?
Kristen> %.2f,var
Close. Try this:
>>> val = 1.1
>>> val
1.1000000000000001
>>> "%.2f" % val
'1.10'
In the common case (the one most like C), it takes a string containing
typical %-format stuff on the left and a tuple of strings on the
right:
>>> "%.2f %.3f %.4f" % (val, val, val)
'1.10 1.100 1.1000'
The one-element case can be reduced to a string on the right as in my
first example.
The cooler case takes a dict on the right and slightly different
format characters on the left:
>>> "%(val).2f %(val).3f %(val).4f" % {"val": val}
'1.10 1.100 1.1000'
This is generally helpful where you are interpolating a large string
with many %-expressions and would find it difficult to match up the
%-format elements with the index positions of the tuple.
Normally, the values you want to interpolate are local variables, so
you see it often spelled as
>>> "%(val).2f %(val).3f %(val).4f" % locals()
'1.10 1.100 1.1000'
People have also developed tricks for interpolating with multiple
dictionaries at once and interpolating expressions on-the-fly. Search
the recent archives of the list (last two months or so) for
"interpolat" to find example code.
Skip
More information about the Python-list
mailing list