• 020 格式化输出的三种方法


    程序中经常会有这样场景:要求用户输入信息,然后打印成固定的格式

    比如要求用户输入姓名、身高、体重,然后打印如下格式:My name is xucheng, my height is 180, my weight is 140

    如果使用字符串拼接的方法进行输出会比较麻烦。比如:

    name = 'xucheng'
    height = 180
    weight = 140
    # 字符串拼接方式打印信息
    print("My name is "+xucheng+", my height is "+height+"my weight is"+weight)
    

    既然python的语法就是以简便著称,那么一定有更简便的方法。

    下面来以此介绍python中的三种格式化输出的方法

    一、占位符

    使用方法:

    使用%s(针对所有数据类型)、%d(仅仅针对数字类型)进行字符串输出占位。并在要打印的字符串后%(变量名)

    如:

    name = 'xucheng'
    height = 180
    weight = 140
    # 使用占位符方式打印信息
    print("My name is %s, my height is %s, my weight is %s"  % (name, height, weight))
    print("My name is %s"  % name)
    print("My height is %s"  % height)
    print("My weight is %s"  % weight)
    

    输出信息:
    My name is xucheng, my height is 180, my weight is 140
    My name is xucheng
    My height is 180
    My weight is 140

    二、format格式化

    个人认为,format方法是三钟格式化输出中最鸡肋的方法。平常根本用不到,推荐大家使用下面的第三种方法f-string格式化!

    使用方法:

    在打印的字符串中使用{这里可以填入后面变量的索引值},并在字符串后.format(多个变量用逗号隔开)

    如:

    name = 'xucheng'
    height = 180
    weight = 140
    # 使用format格式化方式打印信息
    print("My name is {}, my height is {}, my weight is {}".format(name, height, weight))
    print("My name is {0}, my height is {1}, my weight is {2}".format(name, height, weight))
    print("My name is {2}, my height is {1}, my weight is {0}".format(weight, height, name))
    

    输出信息:
    My name is xucheng, my height is 180, my weight is 140
    My name is xucheng, my height is 180, my weight is 140
    My name is xucheng, my height is 180, my weight is 140

    三、f-String格式化

    相比较占位符的方式,python3.6版本新增了f-String格式化的方式,比较简单易懂,这是目前我用的最多的方式,推荐使用这种方式。

    使用方法:

    在字符串前加f(大写小写都可以)并在字符串中要填入的变量处输入{这里面填想要的变量}

    如:

    name = 'xucheng'
    height = 180
    weight = 140
    # 使用f-String格式化方式打印信息
    print(f"My name is {name}, my height is {height}, my weight is {weight}")
    

    输出信息:
    My name is xucheng, my height is 180, my weight is 140

    关于f-String格式化的扩展方法

    {<参数序号> : <格式控制标记>}

    : <填充> <对齐> <宽度> <,> <.精度> <类型>
    引导符号 用于填充的单个字符 < 左对齐 > 右对齐 ^ 居中对齐 槽设定的输出宽度 数字的千位分隔符 浮点数小数 或 字符串最大输出长度 整数类型 b,c,d,o,x,X 浮点数类型e,E,f,%
    s = 'xucheng'
    print(f'{s:*^10}')  # :表示后面的字符有意义,*表示填充的字符,^中间;<居左;>居右,10表示填充的字符长度
    
    height = 180.01
    print(f'{height:.3f}')  # .精度
    

    输出信息:
    xucheng*
    180.010

  • 相关阅读:
    php 显示文件 与Windows文件名排序一致
    pip3 install uwsgi 报错
    centos7 安装mysql 5.7
    Win7 开始菜单搜索添加快捷方式
    centos7.7 clamav 查杀病毒
    CentOS7.x 默认php版本与php7.4共存
    centos6.5 yum安装redis
    centos6 yum安装mysql 5.6 (完整版)
    解决phpmyadmin出现: Maximum execution time of 300
    Castle Windsor 使MVC Controller能够使用依赖注入
  • 原文地址:https://www.cnblogs.com/XuChengNotes/p/11277869.html
Copyright © 2020-2023  润新知