f-string with float formatting in list-comprehension

£可爱£侵袭症+ 提交于 2020-01-24 08:59:25

问题


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


来源:https://stackoverflow.com/questions/48255952/f-string-with-float-formatting-in-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!