【发布时间】:2018-06-23 16:02:43
【问题描述】:
用于字符串格式化的[f'str'] 最近在 python 3.6 中引入。 link。我正在尝试比较 .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'中的float可以实现:
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() 方法使用f'str' 实现与上面相同的输出?
谢谢。
【问题讨论】:
-
你为什么要在 f 字符串 inside 中进行列表理解?对于
.format()版本,您没有这样做。看起来你知道该怎么做,你只需要不要搞砸了。 -
如果我在列表 comp 之外执行它,它不会相应地修改每个元素。我想看看
f'str'可以使用什么类型的expr。 -
您正在在列表 comp 之外进行操作。 “不会相应地修改每个元素”是什么意思?
-
我需要它来迭代地修改列表中的每个元素,就像使用
.format()所做的那样试图弄清楚如何使用列表理解将[0.0, 15.555555555555557, 38.88888888888889]的输出['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']和f'str'带到['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']. -
再说一遍:你已经证明你已经知道该怎么做了。
标签: python string list-comprehension python-3.6 number-formatting