List comprehension and string conversion with formatting

Carl Banks pavlovevidence at gmail.com
Tue Jun 9 11:43:12 EDT 2009


On Jun 9, 8:38 am, stephen_b <redplusbluemakespur... at gmail.com> wrote:
> I'd like to convert a list of floats to a list of strings constrained
> to one .1f format. These don't work. Is there a better way?
>
> [".1f" % i for i in l]
> or
> [(".1f" % i) for i in l]

You need a % in there, chief.

[ "%.1f" % x for x in lst ]

BTW, I took the liberty of making a few style choices, highly
recommended: not to use "i" for floating points ("i" strongly suggests
integer value to many programmers), and not using "l" (the letter ell)
as a name, it can be hard to distinguish from a "1" (the number one).


Carl Banks



More information about the Python-list mailing list