f-string with float formatting in list-comprehensi

2019-07-09 23:32发布

问题:

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.

回答1:

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']