python 字符串格式化输出

1. python 字符串格式化输出

  • 示例代码

    # 变量赋值
    name = "张三"
    avg = 22
    height = 1.75
    
  • 方法1、使用(%s %d %f ) 格式化输出

    print("我的名字叫:%s ,我的年龄是:%d , 我的升高是%0.2f 米 " %(name,avg,height))
    
  • 方法2、使用( format )格式化输出

    print("我的名字叫:{} ,我的年龄是:{} , 我的升高是{:.2f} 米 ".format(name,avg,height))
    
  • 方法3、使用简写( f )格式化输出

    print(f"我的名字叫:{name} ,我的年龄是:{avg} , 我的升高是{height} 米 ")
    

2. 案例

  • 案例1、使用%s %d %f 格式化输出

    #!/usr/bin/env python3
    # _*_ coding: utf-8 _*_
    # Author:shichao
    # File: .py
    
    # 变量赋值
    name = "张三"
    avg = 22
    height = 1.75
    
    
    print("我的名字叫:%s ,我的年龄是:%d , 我的升高是%0.2f 米 " %(name,avg,height))
    
    
  • 案例2、使用format格式化输出

    #!/usr/bin/env python3
    # _*_ coding: utf-8 _*_
    # Author:shichao
    # File: .py
    
    # 变量赋值
    name = "张三"
    avg = 22
    height = 1.75
    
    
    print("我的名字叫:{} ,我的年龄是:{} , 我的升高是{:.2f} 米 ".format(name,avg,height))
    
  • 案例3、使用f简写方法格式化输出

    #!/usr/bin/env python3
    # _*_ coding: utf-8 _*_
    # Author:shichao
    # File: .py
    
    # 变量赋值
    name = "张三"
    avg = 22
    height = 1.75
    
    print(f"我的名字叫:{name},我的年龄是:{avg}, 我的升高是{height} 米 ")
    
posted @ 2022-12-26 11:28  七月流星雨  阅读(149)  评论(0编辑  收藏  举报