zoukankan      html  css  js  c++  java
  • Python中字符串的format

    用法:

      它通过{}和:来代替传统%方式

    1、使用位置参数

    要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表

    list0 = ['hcq', 20]
    str0= "my name is {}, age {}".format("hcq", 20)
    print(str0)
    str1 = 'my name is {1} ,age {0}'.format(20, 'hcq')
    print(str1)
    str2 = 'my name is {1} ,age {0} {1}'.format(20, 'hcq')
    print(str2)
    str3 = 'my name is {} ,age {}'.format(*list0)
    print(str3)
    

      

    2、使用关键字参数

    要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可

    dict0 = {'name': 'hcq', 'age': 20}
    str0 = "my name is {name}, age {age}".format(name = "hcq", age = 20)
    print(str0)
    str1 = 'my name is {name} ,age {age}'.format(**dict0)
    print(str1)
    

      

    3、填充与格式化

    :[填充字符][对齐方式 <^>][宽度]

    str0 = "{0:*>10}".format(10)  # 右对齐
    print(str0)
    str1 = "{0:*<10}".format(8)  # 左对齐
    print(str1)
    str2 = "{0:*^10}".format(3)  # 居中对齐
    print(str2)
    

      4、精度和进制

    str0 = "{0:.2f}".format(1/3)
    print(str0)
    str1 = "{0:b}".format(10)
    print(str1)
    str2 = "{0:o}".format(10)
    print(str2)
    str3 = "{0:x}".format(10)
    print(str3)
    str4 = "{:,}".format(123456798456)
    print(str4)
    

      5、使用索引

    list0 = ["hcq", 20]
    str0 = "name is {0[0]} age is {0[1]}".format(list0)
    print(str0)
    

      主要参考:https://www.cnblogs.com/benric/p/4965224.html

  • 相关阅读:
    chrome rpm旧版本下载地址
    windows 静态绑定arp
    ubuntu20开机自动打开浏览器全屏访问指定页面
    nginx+uwsgi+django+systemd部署django项目
    openresty编译安装
    windows服务器设置定时重启
    华为云和AWS之间打通内网
    python glob
    python subprocess
    python 异常
  • 原文地址:https://www.cnblogs.com/qunqun/p/8877924.html
Copyright © 2011-2022 走看看