1

I have a list of floats like following:

numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

I want to format it so that I could print up to 4 decimal places. So, I wrote the following code:

for x in numbers:
    print("{:10.04f}".format(x))

It prints following, i.e., each number in a separate line.

   23.2300
    0.1233
    1.0000
    4.2230
 9887.2000

However, I want to print all of them on the same line. Using following code, I could achieve this.

print('{:10.4f}{:10.4f}{:10.4f}{:10.4f}{:10.4f}'.format(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4]))

And I got this:

   23.2300    0.1233    1.0000    4.2230 9887.2000

My question is: Is there any better way to achieve this without explicitly writing each element of the list using a loop? I have a list of 110 entries and writing each explicitly each element so many times is painful.

Pankaj
  • 519
  • 2
  • 5
  • 20

2 Answers2

5

How about:

print(' '.join("{:10.04f}".format(x) for x in numbers))

See String join()

Within the join(), we apply the format to each element in the list of numbers.

Aditya Barve
  • 1,351
  • 1
  • 9
  • 13
2

The print built-in methon has an "end" keyword argument which defaults to a linebreak. You just need to replace it with a space or tab, like so:

print("{:10.04f}".format(x), end="\t")

Check https://docs.python.org/3/library/functions.html?highlight=print#print for more information on it.

e_gnite
  • 48
  • 1
  • 5