zoukankan      html  css  js  c++  java
  • python的格式化输出

    一,%号形式输出

    1,整数的输出

    %o--------------otc八进制  例如:print   ‘%o’ % 20======》24

    %d--------------dec十进制  例如:print  ‘%d’  %20=======》20

    %x---------------hex十六进制  例如:print  ‘%x’   % 20 ====》14

    2,浮点数输出

    (1)格式化输出

    %f---------------保留小数点后面六位有效数字   例如:%.3f,保留3位小数点位  print ‘%f’ %1.11=======》1.110000 ;print '%.1f' %1.11======>1.1

    %e--------------保留小数点后面六位有效数字   例如:%.3e,保留3位小数点位,使用科学计数法print ‘%e’ %1.11========>1.110000e+00;print  ‘%.3e’ %1.11 ======》1.110e+00

       (2)  内置round()

    round(number[,ndigits]) 该方法返回x的小数点舍入n位数后的值

    例如:round(1.1124)#四舍五入,不指定位数,取整数===》1          round(1.1125,3)=====》1.113

    3,字符串输出

    %s

    %10s===右对齐,占位符10位(也就是10个字符的位置大小)

    %-10s===左对齐,占位符10位

    %.2s=====截取2位字符串

    %10.2s=====10位占位符,截取两位字符串  例如:print ‘10.2’ %‘hello world’  右对齐,取2位          he

    二,format形式输出

    相对基本格式化输出‘%’的方法,format()功能更为强大,该函数把字符串当成一个模版,通过传入的参数进行格式化,并且使用{}作为特殊字符代替‘%’

    使用方法有两种:b.format(a)和format(a,b)

    1,基本用法

         (1)不带编号,即{}     例如:print ‘{}  {}’.format('hello','workd')

           (2)  带数字编号,可以调换顺序,即{1},{2}     例如:print ‘{0} {1}’.format('hello','world')

        (3)带关键字,即‘{a}’{tom}    例如:print ‘{a} {tom} {a}'.format(tom='hello',a='world')

    2、进阶用法

    (1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐

    (2)取位数“{:4s}”、"{:.2f}"等

    >>> print('{} and {}'.format('hello','world')) # 默认左对齐
    hello and world
    >>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左对齐,取10位右对齐
    hello and world
    >>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中间对齐
    hello and world
    >>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
    1.123 is 1.12
    >>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位
    1.123 is 1.12

    3、多个格式化

    'b' - 二进制。将数字以2为基数进行输出。
    'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。
    'd' - 十进制整数。将数字以10为基数进行输出。
    'o' - 八进制。将数字以8为基数进行输出。
    'x' - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
    'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。
    'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
    'n' - 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。
    '%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号。

    >>> print('{0:b}'.format(3))
    11
    >>> print('{:c}'.format(20))
    
    >>> print('{:d}'.format(20))
    20
    >>> print('{:o}'.format(20))
    24
    >>> print('{:x}'.format(20))
    14
    >>> print('{:e}'.format(20))
    2.000000e+01
    >>> print('{:g}'.format(20.1))
    20.1
    >>> print('{:f}'.format(20))
    20.000000
    >>> print('{:n}'.format(20))
    20
    >>> print('{:%}'.format(20))
    2000.000000%
    >>>

  • 相关阅读:
    JQuery DOM操作
    JQuery 选择器和事件
    LinQ 组合查分页
    LinQ
    web 图片验证码 验证
    Web 上传图片加水印
    Web 组合查询加 分页
    ajax连接数据库加载+三级联动
    jq动画
    jq基础
  • 原文地址:https://www.cnblogs.com/lpfworld/p/9333057.html
Copyright © 2011-2022 走看看