Issue
I want to print a list of numbers, but I want to format each member of the list before it is printed. For example,
theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]
I want the following output printed given the above list as an input:
[1.34, 7.42, 6.97, 4.55]
For any one member of the list, I know I can format it by using
print "%.2f" % member
Is there a command/function that can do this for the whole list? I can write one, but was wondering if one already exists.
Solution
If you just want to print the numbers you can use a simple loop:
for member in theList:
print "%.2f" % member
If you want to store the result for later you can use a list comprehension:
formattedList = ["%.2f" % member for member in theList]
You can then print this list to get the output as in your question:
print formattedList
Note also that %
is being deprecated. If you are using Python 2.6 or newer prefer to use format
.
Answered By - Mark Byers
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.