我想在数字前附加一个加号。我已经在使用格式说明符:
"{0:+03f}".format(x)
我也听说过这两个,但我不知道如何使用它们:
"%+d" or "%+f"
我对第一个的问题是格式后的数字是浮点型。
例如,我正在编写一个计算二次函数的小程序,但我对这样的输出不满意:
f(x) = 2x^2+2.000x-4.000000
那些零让它看起来很奇怪。
如果不是上述情况,是否有任何解决方案可以在什么都没有时去掉零,但在点后只有零?
最佳答案
也许 %g
就是您要找的东西?
>>> '%+g' % 2.
'+2'
>>> '%+g' % 2.1
'+2.1'
>>> '%+g' % 2.10001
'+2.10001'
%g
的确切定义如下:
General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.
The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.
Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.
A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.
( source .)
与 format()
类似:
>>> '{0:+g}'.format(2.)
'+2'
>>> '{0:+g}'.format(2.1)
'+2.1'
>>> '{0:+g}'.format(2.1001)
'+2.1001'
关于python - 在正数前附加一个加号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53647456/