zoukankan      html  css  js  c++  java
  • Python中三种格式化输出的方式

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

    比如要求用户输入用户名和年龄,然后打印如下格式:

    # a = "------------- info -------------"
    # b = "name:"
    # c = "age:"
    # d = "job:"
    # e = "-------------- end -------------"
    # name = input("name")
    # age = input("age")
    # job = input("job")
    # print(a + "
    " + b + name + "
    " + c + age + "
    "+ d + job + "
    " +e)
    
    

    那么这样实现特别繁琐,代码不简洁,而且繁琐,那么这时候就要用到字符串的格式化输出:
    第一种 利用%(称之为:占位符)格式化输出:

    
    # s = """ ------------- info -------------
    # name:%s
    # age:%s
    # job:%s
    # -------------- end -------------
    # """
    # name = input("name")
    # age = int(input("age"))
    # job = input("job")
    # print(s%(name,age,job))
    

    这样就没有上面看起来那么冗余
    第二种 : f-String格式化(第二种格式化输出)(3.6版本,具有向上兼容)建议使用使打印更加好看

    print(f"你是谁{任意的变量,和参数}")
    print(f"{alxe * 2}")#可以任意的运算
    name = 'wupeiqi'
    age = 3
    print(f"hello,{name},you are {age}")
    #输出:
    hello,wupeiqi,you are 30
    
    

    第三种 :利用format格式化输出format格式化(第三种格式化输出)(3.4版本,具有向上兼容)

    name = '阿瓦达所'
    age = 30
    print("hello,{},you are {}".format(name,age))
    #输出:
    hello,阿瓦达所,you are 30
    
    name = 'alxsasd'
    age = 30
    print("hello,{1},you are {0}".format(age,name))#索引是根据format后的数据进行的哦
    #输出:
    hello,alxsasd,you are 30
    
    name = '沛'
    age =78
    print("hello,{name},you are {age}".format(age=age, name=name))
    #输出:
    hello,沛,you are78
    
  • 相关阅读:
    Pymongo
    asp.net mvc4 使用java异步提交form表单时出现[object object] has no method ajaxSubmit
    C# Activator.CreateInstance()
    GridView中某一列值的总和(web)
    02.[WPF]如何固定窗口的大小
    01.WPF中制作无边框窗体
    C#.net时间戳转换
    org.springframework.beans.factory.BeanCreationException: 求教育!
    log4Net配置详解
    SQL语句-创建索引
  • 原文地址:https://www.cnblogs.com/wuzifan/p/11426434.html
Copyright © 2011-2022 走看看