美文网首页
Python 格式化输出的3种方式

Python 格式化输出的3种方式

作者: R_zb | 来源:发表于2019-11-14 01:11 被阅读0次

第一种: %

  • 单个使用格式:“%s” % “test”

  • 多个使用格式:“年份:%d,月份:%d, 日期:%d” % (2019,11,13)

    注:多个使用时,需按顺序填充,且格式内容需与符号对应(如%d取值str内容,则会报错)

  • Python 字符串格式化符号:

    符号 描述
    %c 格式化字符及其ASCII码
    %s 格式化字符串
    %d 格式化整数
    %u 格式化无符号整型
    %o 格式化无符号八进制数
    %x 格式化无符号十六进制数
    %X 格式化无符号十六进制数(大写)
    %f 格式化浮点数字,可指定小数点后的精度
    %e 用科学计数法格式化浮点数
    %E 作用同%e,用科学计数法格式化浮点数
    %g %f和%e的简写
    %G %F 和 %E 的简写
    %p 用十六进制数格式化变量的地址
# 顺序取值
test = "年份:%s,月份:%s" % ("2019", "11")
print(test)     # 年份:2019,月份:11

test = "年份:%d,月份:%d" % (2019, 11)
print(test)     # 年份:2019,月份:11

# 格式字符串的参数顺序填错
test = "年份:%d,月份:%d" % (11, 2019)
print(test)     # 年份:11,月份:2019

# 格式字符串的参数格式错误
test = "年份:%d,月份:%s" % ("2019", "11")
print(test)
# 报错:TypeError: %d format: a number is required, not str

# 格式字符串的参数不足
test = "年份:%d,月份:%d" % (2019)
print(test)
# 报错:TypeError: not enough arguments for format string

第二种 :str.format()

  • 默认顺序取值

  • 下标取值

  • 变量取值

    # 默认顺序
    test = "年份:{},月份:{}".format(2019, 11)
    print(test)   # 年份:2019,月份:11
    
    # 下标
    test = "年份:{1},月份:{0}".format(2019, 11)
    print(test)   # 年份:11,月份:2019
    
    # 下标(多次使用)
    test = "年份:{1},月份:{0},年份:{1}".format(2019, 11)
    print(test)   # 年份:11,月份:2019,年份:11
    
    # 变量
    test = "年份:{year},月份:{month}".format(year=2019, month=11)
    print(test)   # 年份:2019,月份:11
    

第三种:f“ ”

year = 2019
month = 11
# 调用变量
print(f"年份:{year},月份:{month}")  # 年份:2019,月份:11
# 调用表达式
print(f"{2 * 100}")     # 200


def hi():
    return "hello"


# 调用函数
print(f"{hi()}")    # hello

# 调用列表下标
test = [2019, 11]
print(f"年份:{test[0]},月份:{test[1]}")     # 年份:2019,月份:11

# 调用字典
test = {"year": 2019, "month": 11}
print(f"年份:{test['year']},月份:{test['month']}")      # 年份:2019,月份:11

相关文章

  • Python自学笔记Day9

    Python自学笔记——Day9 基本输入输出 1. 输出函数及格式化 Python两种输出值的方式: 表达式语句...

  • 实战

    python的格式化输出 #python格式化输出 ##%对于未知变量类型,用这样就不太方便了 name='lis...

  • 入门输入输出篇

    python 的输入和输出 输出 print('hello') 格式化输出: 命令行: >>> 'Hello, %...

  • Python 中的常见 格式化符号

    Python 认识格式化输出 中的 格式化符号 在前面的文章里我们早早就接触过Python中的输出的函数prinn...

  • Python2与Python3中print用法总结

    Python2中的print用法 在Python2 中 print 是一种输出语句 1.格式化输出整数 2.格式化...

  • python—输入与输出

    Python的格式化输出 使用字符串格式化的形式来优化Python的输出,使用%作为占位符。%后面跟的是变量的类型...

  • python3测试工具开发快速入门教程7输入和输出

    python有多种输出方式:屏幕打印数据,或者写入文件。 格式化输出 我们有两种大相径庭地输出值方法:表达式语句*...

  • Python print 格式化输出

    format 的使用方式如下: 输出为: 另,格式化输出 %s 和 %d 参见:格式化输出 %s 和 %d

  • 13 | 格式化输出

    简单介绍 字符串的格式化输出目前有两种方式 % 方式(陈旧) python2.x及以上 都支持 str.form...

  • python笔记

    Python format格式化输出 浅谈 Python 的 with 语句 Python中迭代原理生成器和迭代原...

网友评论

      本文标题:Python 格式化输出的3种方式

      本文链接:https://www.haomeiwen.com/subject/augkictx.html