美文网首页
Python中格式化输出 %s、%d、%f 的区别

Python中格式化输出 %s、%d、%f 的区别

作者: 一个大橙子Orange | 来源:发表于2019-12-17 18:06 被阅读0次

    1.转换说明符

    %a(%A)    浮点数、十六进制数字和p-(P-)记数法(C99)
    %c        字符
    %d        有符号十进制整数
    %f        浮点数(包括float和doulbe)
    %e(%E)    浮点数指数输出[e-(E-)记数法]
    %g(%G)    浮点数不显无意义的零"0"
    %i        有符号十进制整数(与%d相同)
    %u        无符号十进制整数
    %o        八进制整数,例:print('%o' %1234)  Run:2322
    %x(%X)    十六进制整数0f(0F),例:print('%x' % 100)  Run:64
    %p        指针
    %s        字符串
    %%        "%" 
    

    2.标志

    -        左对齐
    +        右对齐
    

    3.格式字符串(格式)

    〔标志〕〔输出最少宽度〕.〔精度〕〔长度〕〔类型〕
    %[(name)] [flags] [width] . [precision] typecode
    "%-md"     左对齐,若m比实际少时,按实际输出。
    #例①:print ('首%-10d尾'%9)  Run:首9         尾;
    #例②:print ('首%-10d尾'%987654321987654321)  Run:首987654321987654321尾
    
    打印字符串
    print ('My name is %s'%'大橙子')
    My name is 大橙子
    
    打印整数
    print ('Im %d years old'%29)
    Im 29 years old
    
    打印浮点数
    print ('My height is %f m'%1.78)
    My height is 1.780000 m
    
    打印浮点数(指定保留小数点位数)
    print ('My height is %.1f m'%1.78)
    My height is 1.8 m
    
    指定占位符宽度
    print('Name:%10s,Age:%8d,Height:%8.2f'% ('大橙子', 29, 1.78))
    Name:       大橙子,Age:      29,Height:    1.78
    
    指定占位符宽度(左对齐)
    print('Name:%-10s,Age:%-8d,Height:%-8.2f'% ('大橙子', 29, 1.78))
    Name:大橙子       ,Age:29      ,Height:1.78 
    
    指定占位符(只能用0当占位符)
    print('Name:%10s,Age:%08d,Height:%08.2f'% ('大橙子', 29, 1.78))
    Name:       大橙子,Age:00000029,Height:00001.78
    
    科学计数法
    print(format(0.0015,'.2e'))
    1.50e-03
    
    赋值宽度、精度
    print('首%*.*s尾'%(20,2,'ABCDEF'))
    首                  AB尾
    

    相关文章

      网友评论

          本文标题:Python中格式化输出 %s、%d、%f 的区别

          本文链接:https://www.haomeiwen.com/subject/nqisnctx.html