zoukankan      html  css  js  c++  java
  • python学习-22 字符串格式化

    格式化包括:百分号方式和format方式

    1.百分号

    - %s   (%.4s   表示截取了4个字符)

    传单个值:

    例如:

    print('i am %s sex boy is ljj'%123)

    运行结果:

    i am 123 sex boy is ljj
    
    Process finished with exit code 0

    传多个值:

    print('i am %s sex boy is %s'%('13','ss'))

    运行结果:

    i am 13 sex boy is ss
    
    Process finished with exit code 0

    - %d (只能传数字)

    a= 'i am %s, she is %d'%('xm',123)
    print(a)

    运行结果:

    i am xm, she is 123
    
    Process finished with exit code 0

    -打印浮点数

    a= 'abc %.2f'%99.45678           # .2表示保留小数点后2位(四舍五入)
    print(a)

    运行结果:

    abc 99.46
    
    Process finished with exit code 0

    -打印百分比

    a= 'abc %.2f %%'%99.45678
    print(a)

    运行结果:

    abc 99.46 %
    
    Process finished with exit code 0

    -键值

    a= "i am %(name)s ,and age is %(age)d" % {"name":"ljj","age":18}
    print(a)

    运行结果:

    i am ljj ,and age is 18
    
    Process finished with exit code 0

    -其他方法

    a= "i am %(name)-60s aabbcc" % {"name":"ljj"}    #左对齐60格(+右对齐)
    print(a)

    运行结果:

    i am ljj                                                          aabbcc
    
    Process finished with exit code 0

    2.format方式

    -传值

    a= "i am {},age {},{}" .format("xm",18,123)
    print(a)

    运行结果:

    i am xm,age 18,123
    
    Process finished with exit code 0

    -根据索引取值

    a= "i am {1},age {0}" .format("xm",18,123)
    print(a)

    运行结果:

    i am 18,age xm
    
    Process finished with exit code 0

    -

    a= "i am {name},age {age} " .format(name="xm",age=18)
    print(a)

    运行结果:

    i am xm,age 18 
    
    Process finished with exit code 0
  • 相关阅读:
    logging模块-logging.basicConfig、logger.setLevel、handler.setLevel优先级
    Python标准模块--logging(转载)
    第三节,入门知识和windows系统安装python环境
    第二节windows系统下Xshell 5软件远程访问虚拟机 Linux系统
    第一节windows系统安装虚拟机VMware 软件
    数学数列
    java String
    linux eclipse 报错过时的方法
    java.util.Random 类
    java uitl
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11119774.html
Copyright © 2011-2022 走看看