Python格式函数

2024-05-23 20:44:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个值格式化程序

def formatter(value):
    return '{:.8f}'.format(value)

但是我不想总是回到小数点后8位,我想回到小数点后8位。在

^{pr2}$

我该怎么做? 这是为了应用于一个大数组的数字。当数字不断超出dba设置的限制时,这些数据就会被吸入到sql服务器中。在

谢谢


Tags: 数据程序服务器formatsqlreturnvalueformatter
3条回答

如果stringwidth大于生成数字的字符数,则第一个解决方案不起作用,因为它在字符串周围添加空格,rstrip没有任何效果。在

为了让它工作,首先你应该把它弄圆(必要时剥去),然后,作为第二步-居中。因此,我们有:

numbers = [100, 100.01, 3.1232342341312323434]

for number in numbers:
    rounded_number = '{:.8f}'.format(i).rstrip('0').rstrip('.')
    centered_number = '{:^14}'.format(rounded_number)  # substitute 14 with the desired width
    print (centered_number)

    # Or, as a one-liner
    # print ('{:^14}'.format('{:.8f}'.format(i).rstrip('0').rstrip('.')))

输出:

^{pr2}$

回答您的问题:

只需使用float表示类型'{:g}',而不是{},如Format Specification Mini-Language所述。这将自动丢弃尾随的零。另外,如果需要的话,它会转换成指数表示法。在

def formatter(value):
    return "{:^14.8g}".format(value)

l = [100, 100.01, 3.1232342341312323434,
     0.000000000000123, 1234567899.999]

for x in l:
    print(formatter(x))

输出:

^{pr2}$

格式化程序函数的一些可能有用的扩展

稍微更改格式化程序函数,以便在调用时设置打印字段的精度和宽度:

def formatter(value, precision, width):
    return "{{:^{}.{}g}}".format(width, precision).format(value)

l = [100, 100.01, 3.1232342341312323434,
     0.000000000000123, 1234567899.999]

for x in l:
    print(formatter(x, 5, 20))

输出:

             100              
            100.01            
            3.1232            
           1.23e-13           
          1.2346e+09          

我在这个页面上找到了关于Pandas Formatting Snippets的嵌套format()函数

你可以这样做:

'{:^<stringwidth>.8f}'.format(value).rstrip('0').rstrip('.')

其中stringwidth是所需输出的宽度,其中值应居中。在

相关问题 更多 >