简体   繁体   English

在list-comprehension中使用float格式的f-string

[英]f-string with float formatting in list-comprehension

The [f'str'] for string formatting was recently introduced in python 3.6. 字符串格式化的[f'str']最近在python 3.6中引入。 link . 链接 I'm trying to compare the .format() and f'{expr} methods. 我正在尝试比较.format()f'{expr}方法。

 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: 使用.format()方法,它将结果作为float打印到两个小数点,并添加字符串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: 我正在尝试使用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']

Formatting the float in f'str' can be achieved: 可以实现格式化f'str'的float:

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' ? 是否有可能使用f'str'使用.format()方法实现与上面相同的输出?

Thank you. 谢谢。

You need to put the f-string inside the comprehension: 你需要将f-string放在理解中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM