在Python 3.6中引入了[f'str']
字符串格式化方法。链接。我正在尝试比较.format()
和f'{expr}'
两种方法。
f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '
以下是一个列表推导式,将华氏度转换为摄氏度。
使用.format()
方法将结果打印为浮点数,保留两位小数,并添加字符串“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}
方法复制上述内容:
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'
中格式化浮点数来实现:
n = 10
print(f'{n:.2f} Celsius') # prints 10.00 Celsius
尝试将其实现到列表推导式中:
print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]:.2f}') # This will produce a TypeError: unsupported format string passed to list.__format__
使用方法能否实现与上面使用
.format()
方法相同的输出结果?谢谢。
.format()
版本中,你并没有这样做。看起来你知道如何做,只需要不搞砸就行了。 - Stefan Pochmannf'str'
中可以使用什么类型的 expr。 - Novice.format()
方法一样。我正在试图弄清如何使用列表推导式将输出[0.0, 15.555555555555557, 38.88888888888889]
转换为['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']
并使用f'str'
。 - Novice