列表理解中带浮点格式的f字符串

Nov*_*ice 4 python string list-comprehension number-formatting python-3.6

[f'str']字符串格式化在Python 3.6是近期推出。链接。我正在尝试比较.format()f'{expr}方法。

 f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '
Run Code Online (Sandbox Code Playgroud)

以下是将华氏温度转换为摄氏温度的列表理解。

使用该.format()方法将结果以浮点数打印到两个小数点,并添加字符串摄氏:

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']
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用f'{expr}方法复制以上内容:

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']
Run Code Online (Sandbox Code Playgroud)

格式化浮动f'str'可以实现:

n = 10

print(f'{n:.2f} Celsius') # prints 10.00 Celsius 
Run Code Online (Sandbox Code Playgroud)

尝试将其实现到列表理解中:

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

是否有可能获得与使用using .format()方法相同的输出f'str'

谢谢。

Dar*_*aut 9

您需要将f字符串放入理解中:

[f'{((x - 32) * (5/9)):.2f} Celsius' for x in Fahrenheit]
# ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']
Run Code Online (Sandbox Code Playgroud)