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

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

我该怎么做?让我们这么说吧

a = 10.1234

当前回答

仅仅

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

输出:10.1

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

输出:10.12

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

输出:10.123

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

输出:10.1234

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

其他回答

在格式表达式中包含类型说明符:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
Consider:
>>> number1 = 10.1234
>>> f'{number1:.2f}'
'10.12'
Syntax:
"{" [field_name] ["!" conversion] [":" format_spec] "}"
Explanation:
# Let's break it down...
#       [field_name]     => number1
#       ["!" conversion] => Not used
#       [format_spec]    => [.precision][type] 
#                        => .[2][f] => .2f  # where f means Fixed-point notation

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

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    ::=  identifier
    element_index     ::=  digit+ | index_string
    index_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-字符串语法

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

WIDTH = 7
PRECISION = 3
TYPE = "f"

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

其他格式请参见:https://docs.python.org/3.6/library/string.html#format-规范小型语言


参考:其他SO答案

仅仅

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

输出:10.1

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

输出:10.12

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

输出:10.123

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

输出:10.1234

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

a = 10.1234

print(f"{a:0.2f}")

在0.2f中:

0告诉python不限制陈列.2表示我们只想在小数后取2位(结果将与round()函数相同)f表示它是一个浮点数。如果你忘记了f,那么它只会在小数点后少打印1个数字。在这种情况下,它只能是小数后1位。

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