使用f-strings修正十进制后的数字

Gaf*_*112 218 python python-3.x f-string

Python f字符串(PEP 498)有一个简单的方法来修复小数点后的位数吗?(特别是f-strings,而不是其他字符串格式化选项,如.format或%)

例如,假设我想在小数位后面显示2位数.

我怎么做?

a = 10.1234

f'{a:.2}'
Out[2]: '1e+01'

f'{a:.4}'
Out[3]: '10.12'

a = 100.1234

f'{a:.4}'
Out[5]: '100.1'
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,"精度"已经改变了"小数点后的位数"的含义,就像使用%格式时的情况一样,只是总数.无论我有多大的数字,我怎么能总是得到小数点后的2位数?

Rob*_*obᵩ 330

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

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
Run Code Online (Sandbox Code Playgroud)

  • 我找到的f-string格式化示例(包括PEP)都没有显示您可以使用类型说明符.我想我应该假设,但是调用它的文档会很好. (19认同)
  • 另请注意,如果没有 f,如果您写 - f'{a:.2}' 它将计算总位数,答案将为 10 (8认同)
  • 哦,男人,这很华丽,很简单.为什么我需要超过45秒才能找到这个答案?在游戏中,谷歌. (6认同)
  • @tarabyte - f 字符串在 3.6 中引入。3.5.2 中不存在该语法 https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498 (2认同)

lmi*_*asf 61

float数字方面,您可以使用格式说明符:

f'{value:{width}.{precision}}'
Run Code Online (Sandbox Code Playgroud)

哪里:

  • value 是任何计算结果的表达式
  • width指定要显示的总数中使用的字符数,但如果value需要的空间大于宽度指定的空间,则使用额外的空间.
  • precision 表示小数点后使用的字符数

您缺少的是十进制值的类型说明符.在此链接中,您可以找到浮点和小数的可用表示类型.

这里有一些例子,使用f(定点)表示类型:

# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: '     5.500'

# notice that it uses more characters than the ones specified in width
In [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 places
In [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 calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'
Run Code Online (Sandbox Code Playgroud)


Ken*_*war 54

考虑:

>>> number1 = 10.1234
>>> f'{number1:.2f}'
'10.12'
Run Code Online (Sandbox Code Playgroud) 句法:
"{" [field_name] ["!" conversion] [":" format_spec] "}"
Run Code Online (Sandbox Code Playgroud) 解释:
# Let's break it down...
#       [field_name]     => number1
#       ["!" conversion] => Not used
#       [format_spec]    => [.precision][type] 
#                        => .[2][f] => .2f  # where f means Fixed-point notation
Run Code Online (Sandbox Code Playgroud)

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

>>> number1 = 10.1234
>>> f'{number1:.2f}'
'10.12'
Run Code Online (Sandbox Code Playgroud)

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


Nic*_*ais 47

添加到 Rob 的答案中,您可以将格式说明符与f 字符串一起使用更多信息请点击此处)。

  • 您可以控制小数位数
pi = 3.141592653589793238462643383279

print(f'The first 6 decimals of pi are {pi:.6f}.')
Run Code Online (Sandbox Code Playgroud)
The first 6 decimals of pi are 3.141593.
Run Code Online (Sandbox Code Playgroud)
  • 您可以转换为百分比
grade = 29/45

print(f'My grade rounded to 3 decimals is {grade:.3%}.')
Run Code Online (Sandbox Code Playgroud)
My grade rounded to 3 decimals is 64.444%.
Run Code Online (Sandbox Code Playgroud)
  • 您可以执行其他操作,例如打印常量长度
from random import randint
for i in range(5):
    print(f'My money is {randint(0, 150):>3}$')
Run Code Online (Sandbox Code Playgroud)
My money is 126$
My money is   7$
My money is 136$
My money is  15$
My money is  88$
Run Code Online (Sandbox Code Playgroud)
  • 甚至用逗号千位分隔符打印:
print(f'I am worth {10000000000:,}$')
Run Code Online (Sandbox Code Playgroud)
I am worth 10,000,000,000$
Run Code Online (Sandbox Code Playgroud)


Bou*_*ner 26

添加到Robᵩ的答案:如果你想要打印相当大的数字,使用千位分隔符可以提供很大帮助(请注意逗号).

>>> f'{a*1000:,.2f}'
'10,123.40'
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,高五的逗号 - 谁能在没有逗号的情况下读取大数字? (2认同)

Muh*_*oni 13

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

WIDTH = 7
PRECISION = 3
TYPE = "f"

v = 3
print(f"val = {v:{WIDTH}.{PRECISION}{TYPE}}")
Run Code Online (Sandbox Code Playgroud)

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


参考:其他SO答案


Abu*_*dik 5

简单地

a = 10.1234
print(f"{a:.1f}")
Run Code Online (Sandbox Code Playgroud)

输出:10.1

a = 10.1234
print(f"{a:.2f}")
Run Code Online (Sandbox Code Playgroud)

输出:10.12

a = 10.1234
print(f"{a:.3f}")
Run Code Online (Sandbox Code Playgroud)

输出:10.123

a = 10.1234
print(f"{a:.4f}")
Run Code Online (Sandbox Code Playgroud)

输出:10.1234

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