4

I have a list of floats that I would like to print using an f-string: Here is the list

er=[0.3401126304419511,
 0.32561695086083536,
 0.3115512789515306,
 0.21734184387097139,
 0.22354269408531188]

and I want to print them using an f-string as follows:

print(f'{err}')

which produces:

[0.3401126304419511, 0.32561695086083536, 0.3115512789515306, 0.21734184387097139, 0.22354269408531188]

But the following doesn't work:

print(f'{err:.2}')
 Traceback (most recent call last):   
    File "C:\IPython\core\interactiveshell.py", line 3325, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)   
    File "<ipython-input-166-bbcdc82a9939>", line 1, in <module>
        print(f'{err:.2}') 
    TypeError: unsupported format string passed to list.__format__

Is this a bug or a feature? How do I make this work?

I'm using python version:

Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
P Moran
  • 1,624
  • 3
  • 18
  • 32

3 Answers3

2

Here is a way to do it using a list comprehension :

print([f"{x:.2}" for x in er])
vlemaistre
  • 3,301
  • 13
  • 30
  • maybe this doesn't work in some versions of python 3? `$ python3 --version` `Python 3.5.2` `$ python3 -c 'a=list(range(3));print(a)'` `[0, 1, 2]` `$ python3 -c 'a=list(range(3));print(a);print([f"{b}_str" for b in a])'` `File "", line 1` `a=list(range(3));print(a);print([f"{b}_str" for b in a])` `SyntaxError: invalid syntax` – dlamblin Oct 23 '20 at 07:38
  • @dlamblin fstrings were added in Python 3.6 – Gerhard Burger May 13 '21 at 12:23
1

Since, you wish to print the first 2 digits after the decimal of each individual elements. You will have to iterate over it & print them out as -

[f'{element:.2}' for element in er]

Usually we can apply aggregation type functions like len, sumdirectly on a list without needing to iterate over it.

Aditya Mishra
  • 1,687
  • 2
  • 15
  • 24
0

Here, print(f'{er}') is equivalent to print(er). It will output the representation of your list which is as you stated:

[0.3401126304419511, 0.32561695086083536, 0.3115512789515306, 0.21734184387097139, 0.22354269408531188]

When you want to apply f'{err:.2}', what you actually want is to apply this format rule on every element of the list. You will need a for loop or a list comprehension to achieve this.

As suggested in the comments by @Buckeye14Guy, the following should work as expected:

er2 = [f'{el:.2}' for el in er]
print(er2)

Other approach could also work (map) but I guess you have enough to keep it going now.

abrunet
  • 1,122
  • 17
  • 31