【问题标题】:f-string with float formatting in list-comprehension列表理解中具有浮点格式的 f 字符串
【发布时间】: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


【解决方案1】:

您需要将 f-string 放入推导式中:

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

【讨论】:

  • 注意:我只是遇到了一个错误(或者它是一个功能),这意味着它在格式化操作后不允许有空格:f'{0.3456:.2f}' f'{ 0.3456:.2f }' 不起作用!
猜你喜欢
  • 2021-03-30
  • 2023-03-25
  • 2018-05-13
  • 1970-01-01
  • 2021-07-18
  • 2018-07-10
  • 2013-08-11
  • 2018-02-07
  • 1970-01-01
相关资源
最近更新 更多