• python课堂整理8---字符串格式化


    一、字符串格式化(% 和 format)

    1. % s  主要接收字符串类型,也可以接收任意类型

    tp1 = "i am %s my hobby is alex" % 'lhf'
    print(tp1)
    

    tp1 = "i am %s my hobby is %s" % ('lhf', 'dabai')
    print(tp1)
    

    tp1 = "i am %s my age is %d" % ('lhf', 11)
    tp2 = "1 am %s my age is %s" % ('dabai', 12)
    print(tp1, tp2, sep="
    ")
    

    注意:%d 只接收数字,%s接收任意类型,但是最好物尽其用,便于维护!

    2. 打印浮点数,默认保留6位小数,自动四舍五入。

    tp1 = "percent %f"% 99.99675854
    tp2 = "percent %.3f"% 99.99975854
    print(tp1)
    print(tp2)
    

    3. 打印百分比

    tp1 = "percent %.3f%%"% 99.99635854
    print(tp1)
    

    4. 传入值为字典

    tp1 = "i am %(name)s age %(age)d" %{"name": "alex", "age": 18}
    print(tp1)
    

    tp1 = "i am %(pp).2f" % {"pp": 99.99}
    print(tp1)
    

    5. 可选项:+ 右对齐  -左对齐  后面的数字表示宽度, 下面的42控制的颜色

    msg = "i am %(name) + 30s my hobby is dabai" % {'name': 'liu'}
    msg2 = "i am 33[42;1m%(name) + 30s33[0m my hobby is dabai" % {'name': 'liu'}
    print(msg)
    print(msg2)
    

    二、format用法: 

    1. 按顺序对应

    tp1 = "i am {} age {} {}".format("alex", 18, "alex")
    print(tp1)
    

    2. 根据后面索引对应

    tp1 = "i am {2} age {1} {0}".format("alex", 18, "dabai")
    print(tp1)
    

    3. 传入值为字典时,注意前面加两个**

    tp1 = "i am {name} age {age} really {name}".format(name = "alex", age = 18)
    tp2 = "i am {name} age {age} really {name}".format(**{"name": "alex", "age": 18})
    print(tp1)
    print(tp2)
    

    4.索引列表对应

    tp2 = "i am {0[0]} age {0[1]} really {0[2]}".format(["dabai","22","aaa"],[1,2,3])
    print(tp2)
    

    5. 根据类型按顺序输入对应值

    tp2 = "i am {:s} age {:d} really {:.2f}".format("dabai", 18, 99.9)
    print(tp2)
    

    6. 这种类型下,如果传入值为列表,前面要加 * 号

    tp2 = "i am {:s} age {:d} really {:.2f}".format(*["dabai", 18, 99.9])
    print(tp2)
    

    7. 不同进制演示(x:小写16进制, X:大写16进制, o: 8 进制,b : 2进制)

    tp1 = "number: {:b} {:o} {:d},{:x}, {:X}, {:.2%}".format(15, 15, 15, 15,15,15.2341234)
    print(tp1)
    

    tp1 = "number: {0:b} {0:o} {0:d},{0:x}, {0:X}, {0:.2%}".format(15)
    print(tp1)
    

    tp1 = "number: {num:b} {num:o} {num:d},{num:x}, {num:X}, {num:.2%}".format(num = 15)
    print(tp1)
    

    一个奋斗中的产品小白
  • 相关阅读:
    打造基于CentOS7的xfce最简工作环境
    Linux下C程序的编辑,编译和运行以及调试
    修正 XE6 TListView 上方 SearchBok 右边的清除钮显示
    TabControl 显示彩色的图示 (XE6 Firemonkey)
    TSwitch 中文简繁显示支持(XE6 Android)
    改变 TMemo 的背景颜色 (Firemonkey)
    修正 XE5 Android 键盘三个问题
    Delphi 收藏
    展示 Popup 的使用方法
    ListView 下拉更新 (支持 Android)
  • 原文地址:https://www.cnblogs.com/dabai123/p/11007098.html
Copyright © 2020-2023  润新知