固定数字后小数与f字符串

有没有一种简单的方法可以使用Python f字符串来固定小数点后的位数?(特别是f字符串,而不是其他字符串格式选项,如. form或%)

例如,假设我想显示小数点后的2位数字。

a = 10.1234
452224 次浏览

>>> a = 10.1234>>> f'{a:.2f}''10.12'

f'{value:{width}.{precision}}'

# notice that it adds spaces to reach the number of characters specified by widthIn [1]: f'{1 + 3 * 1.5:10.3f}'Out[1]: '     5.500'
# notice that it uses more characters than the ones specified in widthIn [2]: f'{3000 + 3 ** (1 / 2):2.1f}'Out[2]: '3001.7'
In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'Out[3]: ' 3.234500'
# omitting width but providing precision will use the required characters to display the number with the the specified decimal placesIn [4]: f'{1.2345 + 3 * 2:.3f}'Out[4]: '7.234'
# not specifying the format will display the number with as many digits as Python calculatesIn [5]: f'{1.2345 + 3 * 0.5}'Out[5]: '2.7344999999999997'

补充罗布的回答:如果你想打印相当大的数字,使用一千个分隔符会有很大的帮助(注意逗号)。

>>> f'{a*1000:,.2f}''10,123.40'

如果您想填充/使用固定宽度,则宽度为之前逗号:

>>> f'{a*1000:20,.2f}''           10,123.40'

添加到Rob的回答中,您可以将格式说明符与f字符串这里更多)一起使用。

  • 您可以控制小数位数
pi = 3.141592653589793238462643383279
print(f'The first 6 decimals of pi are {pi:.6f}.')
The first 6 decimals of pi are 3.141593.
  • 您可以转换为百分比
grade = 29/45
print(f'My grade rounded to 3 decimals is {grade:.3%}.')
My grade rounded to 3 decimals is 64.444%.
  • 您可以执行其他操作,例如print恒定长度
from random import randintfor i in range(5):print(f'My money is {randint(0, 150):>3}$')
My money is 126$My money is   7$My money is 136$My money is  15$My money is  88$
  • 或者用逗号千分隔符打印:
print(f'I am worth {10000000000:,}$')
I am worth 10,000,000,000$
a = 10.1234
print(f"{a:0.2f}")

在0.2f中:

  • 0告诉python对要访问的总位数没有限制显示
  • .2表示我们只想取小数后的2位数字(结果将与round()函数相同)
  • f表示它是一个浮点数。如果您忘记了f,那么它只会在小数点后少打印1位。在这种情况下,它将只在小数点后1位。

关于数字的f字符串的详细视频https://youtu.be/RtKUsUTY6to?t=606

考虑:
>>> number1 = 10.1234>>> f'{number1:.2f}''10.12'
语法:
"{" [field_name] ["!" conversion] [":" format_spec] "}"
说明:
# Let's break it down...#       [field_name]     => number1#       ["!" conversion] => Not used#       [format_spec]    => [.precision][type]#                        => .[2][f] => .2f  # where f means Fixed-point notation

更进一步,格式字符串具有以下语法。正如您所看到的,还有很多事情可以做。

Syntax: "{" [field_name] ["!" conversion] [":" format_spec] "}"
# let's understand what each field means...field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*arg_name          ::=  [identifier | digit+]attribute_name    ::=  identifierelement_index     ::=  digit+ | index_stringindex_string      ::=  <any source character except "]"> +conversion        ::=  "r" | "s" | "a"format_spec       ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
# Looking at the underlying fields under format_spec...fill            ::=  <any character>align           ::=  "<" | ">" | "=" | "^"sign            ::=  "+" | "-" | " "width           ::=  digit+grouping_option ::=  "_" | ","precision       ::=  digit+type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

参考https://docs.python.org/3/library/string.html#format-string-syntax

简单

a = 10.1234print(f"{a:.1f}")

输出:10.1

a = 10.1234print(f"{a:.2f}")

输出:10.12

a = 10.1234print(f"{a:.3f}")

输出:10.123

a = 10.1234print(f"{a:.4f}")

输出:10.1234

只需更改小数点符号后的值,该符号表示您要打印的小数点。

似乎没有人使用动态格式化程序。要使用动态格式化程序,请使用:

WIDTH = 7PRECISION = 3TYPE = "f"
v = 3print(f"val = {v:{WIDTH}.{PRECISION}{TYPE}}")

其他格式见:https://docs.python.org/3.6/library/string.html#format-specification-mini-language


参考:其他所以回答