List comprehension and string conversion with formatting

S

stephen_b

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]

StephenB
 
C

Carl Banks

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
 
J

Jaime Fernandez del Rio

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]

There's a missing %, this does work...

["%.1f" % i for i in l]

Jaime
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top