zoukankan      html  css  js  c++  java
  • Python %和format的用法

    一、%的用法

    1.整数的输出

    #八进制oct   %o
    print('%o' % 10)  #12
    
    #十进制dec  %d
    print('%d' % 1)  #10
    
    #十六进制hex  %x
    print('%x' % 1)  #a

    2.浮点型数据输出

    # %f 默认保留6位小数  %.1f 保留1位小数
    print('%f,%.1f' % (1.11,1.11))  #1.110000,1.1
    
    #%e  默认保留6位小数,用科学计算法 ,%.1保留1位小数
    print('%e,%.1e' % (1.11,1.11))  #1.110000e+00,1.1e+00
    
    #%g 在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
    print('%g,%.1g' % (1.1111111,1.1111))  #1.11111,1
    print('%g,%.1g' % (11111111.1,11111111))  #1.11111e+07,1e+07

    3.字符串输出

    #%s字符串输出
    print('%s' % 'hi')  #hi
    
    #%ns  右对齐,n位占位符,不够则补位
    print('%10s' % 'hi,hi,hi')  #  hi,hi,hi
    
    #%-ns  左对齐,n位占位符,不够则补位
    print('%-10s' % 'hi,hi,hi')  #hi,hi,hi 
    print('%-10s' % 'hi,hi,hi,hi,hi')  #hi,hi,hi,hi,hi
    
    #%.ns  截取n个字符串
    print('%.2s' % 'hi,hi,hi')  #hi
    
    #%n.ns  整数部分是占位符,小数点是截取n个字符串
    print('%10.2s' % 'hi,hi,hi')  #        hi

    4.format用法

    该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符

    #‘{}’ 最简单格式
    print('{},{}'.format('hello','world'))  #hello,world
    
    #位置编号
    print('{0},{1}'.format('hello','world'))
    print('{0},{1},{0}'.format('hello','world'))  #位置编号,可以输出多次  hello,world,hello
    print('{1},{1}'.format('hello','world'))  #world,world
    
    #关键词
    print('{a},{b}'.format(a='hello',b='world'))  #a,b关键词 hello,world

     较常用的百分比%输出和会计千分位额输出法

    print('{:.2%}'.format(0.12354))   #百分比
    print('{:,}'.format(123456789))   #会计千位分隔符
    print('{:.2f}'.format(31.31412))  #保留2位小数 

     使用list和dict映射

    #list映射,格式是0[i]
    l=list('abcd')
    print('{0[0]},{0[1]},{0[2]},{0[3]}'.format(l))
    
    #dict ,格式是key引用
    dict={'name':'tom','age':20}
    print('name is {name},age is {age}'.format(**dict)) #name is tom,age is 20
  • 相关阅读:
    Rotation Kinematics
    离职 mark
    PnP 问题方程怎么列?
    DSO windowed optimization 代码 (4)
    Adjoint of SE(3)
    IMU 预积分推导
    DSO windowed optimization 代码 (3)
    DSO windowed optimization 代码 (2)
    OKVIS 代码框架
    DSO windowed optimization 代码 (1)
  • 原文地址:https://www.cnblogs.com/cgmcoding/p/13278298.html
Copyright © 2011-2022 走看看