列表理解中带浮点格式的f字符串 [英] f-string with float formatting in list-comprehension
问题描述
最近在python 3.6中引入了用于字符串格式的[f'str']
. 链接.我正在尝试比较.format()
和f'{expr}
方法.
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.
使用.format()
方法将结果以浮点数打印到小数点后两位,并添加字符串摄氏:
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']
我正在尝试使用f'{expr}
方法复制上面的内容:
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']
可以设置f'str'
中的浮点格式:
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__
是否可以通过使用f'str'
的.format()
方法获得与上述相同的输出?
Is it possible to achieve the same output as was done above using the .format()
method using f'str'
?
谢谢.
推荐答案
您需要将f字符串放在理解范围内:
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']
这篇关于列表理解中带浮点格式的f字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!