列表理解中具有浮点格式的 f 字符串
f-string with float formatting in list-comprehension
最近在 python 3.6 中引入了用于字符串格式化的 [f'str']
。 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__
是否可以使用 f'str'
使用 .format()
方法实现与上面相同的输出?
谢谢。
您需要将 f 字符串放入推导式中:
[f'{((x - 32) * (5/9)):.2f} Celsius' for x in Fahrenheit]
# ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']
最近在 python 3.6 中引入了用于字符串格式化的 [f'str']
。 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__
是否可以使用 f'str'
使用 .format()
方法实现与上面相同的输出?
谢谢。
您需要将 f 字符串放入推导式中:
[f'{((x - 32) * (5/9)):.2f} Celsius' for x in Fahrenheit]
# ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']