Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format all elements of a list

Tags:

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.

like image 824
Curious2learn Avatar asked May 04 '10 00:05

Curious2learn


People also ask

Can we format a list in Python?

Format lists and dictionariesThe Python format method accepts a sequence of positional parameters. If we pass an array or a List, then let's find out the result. The whole list gets displayed. You can also decide to print one item from the sequence by providing its index.

How do I format a list to a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


2 Answers

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.

like image 149
Mark Byers Avatar answered Sep 19 '22 09:09

Mark Byers


For Python 3.5.1, you can use:

>>> theList = [1.343465432, 7.423334343, 6.967997797, 4.5522577] >>> strFormat = len(theList) * '{:10f} ' >>> formattedList = strFormat.format(*theList) >>> print(formattedList) 

The result is:

'  1.343465   7.423334   6.967998   4.552258 ' 
like image 34
rvcristiand Avatar answered Sep 19 '22 09:09

rvcristiand