zoukankan      html  css  js  c++  java
  • python格式化字符串format函数

    1. format可以接受无限个的参数,位置可以不按顺序:

    In [1]: "{} {}".format("hello","world") #不设定位置,按默认顺序
    Out[1]: 'hello world'
    
    In [2]: "{0} {1}".format("hello","world") #指定位置
    Out[2]: 'hello world'
    
    In [3]: "{1} {0} {1}".format("hello","world") #指定位置,重复使用参数
    Out[3]: 'world hello world'
    
    In [4]: "{name} {age}".format(name="Linda",age=15)#通过关键字
    Out[4]: 'Linda 15'
    
    # 通过字典设置参数
    In [5]: info = {"name":"Linda","age":15}
    
    In [6]: "{name} {age}".format(**info)
    Out[6]: 'Linda 15'
    
    # 通过列表设定参数
    In [7]: my_list = ['hello','world']
    
    In [8]: "{0[0]} {0[1]}".format(my_list)
    Out[8]: 'hello world'

    2. format格式控制:语法是{}中带冒号(:)

    ^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

    + 表示在正数前显示 +,负数前显示 -;  (空格)表示在正数前加空格

    b、d、o、x 分别是二进制、十进制、八进制、十六进制。

    # 居中显示,长度度为4
    In [9]: "{:^4}".format("he")
    Out[9]: ' he '
    
    # 左对齐,长度为4,空白地方填充"x"
    In [10]: "{:x<4}".format("he")
    Out[10]: 'hexx'
    
    # 显示正负数符号
    In [11]: "{:+}".format(-3)
    Out[11]: '-3'
    
    # 8的二进制显示
    In [12]: "{:b}".format(8)
    Out[12]: '1000'
    
    # 用大括号{}转义大括号
    In [13]: "{} is {{0}}".format("hello")
    Out[13]: 'hello is {0}'
  • 相关阅读:
    实用函数,array_column。从二维数组中获取想要的一位数组。
    解决小程序swiper层级太高问题
    小程序模拟领红包
    小程序,红包弹出层布局
    小程序核销功能
    小程序 text标签中一定 不要换行,不要随便格式化!!!
    小程序动态修改json中的配置
    小程序支付
    docker常用命令
    ssh修改默认端口
  • 原文地址:https://www.cnblogs.com/time-read/p/8317634.html
Copyright © 2011-2022 走看看