python - 在正数前附加一个加号

标签 python python-3.x

我想在数字前附加一个加号。我已经在使用格式说明符:

"{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/

相关文章:

python - 当 edgecolor = 'none' 时 Matplotlib 标记消失

python - 如何使用 tkinter filedialog.askopenfilename 方法避免文件选择器中的隐藏文件?

Python 扩展 - 有效地构造和检查大整数

python - 如何在 matplotlib 中移动刻度标签

python - 如何使用 to_html 将 pandas dataframe 转换为 html 时隐藏列名称

python - 如何使用 Pandas/Matplotlib 绘制 X 轴上的日期、Y 轴上的时间以及 HH :MM format as tick labels? 中的当前时间

python - 使用循环将两个 Pandas 系列按列附加到数据框

python - 将字典的一部分与副本合并

python-3.x - Anaconda提示安装包错误(UnsatisfiableError)

python - 如何使用Python OpenCV在cv2.putText中制作黑色背景