zoukankan      html  css  js  c++  java
  • 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.
    
  • 相关阅读:
    IO—》字节流&字符流
    IO—》递归
    IO—》File类
    IDEA快速升级模块版本号
    redis使用Jackson2JsonRedisSerializer序列化问题
    git 创建管理多用户
    linux后台启动程序脚本实例
    linux 安装配置kafka脚本
    linux 安装配置zookeeper脚本
    linux安装配置JDK脚本
  • 原文地址:https://www.cnblogs.com/yellowcloud/p/10831301.html
Copyright © 2011-2022 走看看