• 4.格式化输出


    格式化输出

    占位符

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

    打印如下格式:My name is xxx,my age is xxx.

    用逗号进行字符串拼接,只能把用户输入的名字和年龄放到末尾,无法放到指定的xxx位置,而且数字也必须经过str(数字)的转换才能与字符串进行拼接。

    age = 19
    print('My name is xxx,my age is '+str(age))
    My name is xxx,my age is 19
    age = 19
    print('My name is xxx,my age is', age)
    My name is xxx,my age is 19
    name = 'nick'
    age = 19
    print('My name is '+name+' my age is '+str(age))
    My name is nick my age is 19
    

    占位符,如:%s(针对所有数据类型)、%d(仅仅针对数字类型)

    name = 'nick'
    age = 19
    print('my name is %s my age is %s' % (name, age))
    my name is nick my age is 19
    age = 19
    print('my age is %d' % age)
    my age is 19
    

    format格式化

    name = 'nick'
    age = 19
    print("Hello, {}. You are {}.".format(name, age))
    Hello, nick. You are 19.
    name = 'nick'
    age = 19
    print("Hello, {1}. You are {0}-{0}.".format(age, name))
    Hello, nick. You are 19-19.
    name = 'nick'
    age = 19
    print("Hello, {name}. You are {age}-{age}.".format(age=age, name=name))
    Hello, nick. You are 19-19.
    

    f-String格式化

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

    name = "nick"
    age = 19
    print(f"Hello, {name}. You are {age}.")
    Hello, nick. You are 19.
    

    大写的F也适用。

    name = "nick"
    age = 19
    print(F"Hello, {name}. You are {age}.")
    Hello, nick. You are 19.
    
  • 相关阅读:
    ue父子组件的数据传递示例
    vue.js 组件之间传递数据
    Vue2.0子同级组件之间数据交互
    assets 和static的区别
    Vue中src属性绑定的问题
    css3设置背景图片的大小
    如何在HTML中插入空格
    css背景图片的设置
    vue动态组件 互相之间传输数据 和指令的定义
    webservice的优缺点
  • 原文地址:https://www.cnblogs.com/yellowcloud/p/10831301.html
Copyright © 2020-2023  润新知