f-string with float formatting in list-comprehension

15,938

You need to put the f-string inside the comprehension:

[f'{((x - 32) * (5/9)):.2f} Celsius' for x in Fahrenheit]
# ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']
Share:
15,938
Novice
Author by

Novice

Updated on June 03, 2022

Comments

  • Novice
    Novice almost 2 years

    The [f'str'] for string formatting was recently introduced in python 3.6. link. I'm trying to compare the .format() and f'{expr} methods.

     f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '
    

    Below is a list comprehension that converts Fahrenheit to Celsius.

    Using the .format() method it prints the results as float to two decimal points and adds the string Celsius:

    Fahrenheit = [32, 60, 102]
    
    F_to_C = ['{:.2f} Celsius'.format((x - 32) * (5/9)) for x in Fahrenheit]
    
    print(F_to_C)
    
    # output ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']
    

    I'm trying to replicate the above using the f'{expr} method:

    print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]}')  # This prints the float numbers without formatting 
    
    # output: [0.0, 15.555555555555557, 38.88888888888889]
    # need instead: ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']
    

    Formatting the float in f'str' can be achieved:

    n = 10
    
    print(f'{n:.2f} Celsius') # prints 10.00 Celsius 
    

    Trying to implement that into the list comprehension:

    print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]:.2f}') # This will produce a TypeError: unsupported format string passed to list.__format__
    

    Is it possible to achieve the same output as was done above using the .format() method using f'str'?

    Thank you.

  • Andy
    Andy over 2 years
    Note: I just ran into a bug (or is it a feature) which means its not allowed to have a space after the formatting operation: f'{0.3456:.2f}' << works | f'{ 0.3456:.2f }' does not work!