继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Python 的内置函数 print

2882716
关注TA
已关注
手记 70
粉丝 0
获赞 0

Python 的内置函数 print() 是最常用的输出函数之一,用于将指定的内容打印到标准输出设备(通常是控制台)。这个函数功能强大且灵活,支持多种参数配置。

基本用法

print("Hello, World!")  # 输出:Hello, World!

参数详解

  1. objects:可以接收多个参数,用逗号分隔

    print("Python", "is", "awesome")  # 输出:Python is awesome
    
  2. sep:指定分隔符(默认是空格)

    print("2023", "05", "20", sep="-")  # 输出:2023-05-20
    
  3. end:指定结尾字符(默认是换行符\n)

    print("Hello", end=" ")
    print("World")  # 输出:Hello World
    
  4. file:指定输出文件对象

    with open('output.txt', 'w') as f:
        print("Save to file", file=f)
    
  5. flush:是否强制刷新缓冲区(默认为False)

    print("Loading...", end="", flush=True)
    

格式化输出

  1. 使用f-string(Python 3.6+)

    name = "Alice"
    print(f"Hello, {name}!")  # 输出:Hello, Alice!
    
  2. 使用format方法

    print("{} is {} years old".format("Bob", 25))
    
  3. 使用%格式化(较老的方式)

    print("Price: %.2f" % 19.99)  # 输出:Price: 19.99
    

实际应用场景

  1. 调试程序时输出变量值

    x = 42
    print(f"Current value: {x}")
    
  2. 显示进度信息

    for i in range(10):
        print(f"Progress: {i+1}/10", end="\r")
    
  3. 生成报表数据

    print("{:<10}{:<10}{:<10}".format("Name", "Age", "Score"))
    print("{:<10}{:<10}{:<10}".format("Alice", "25", "95"))
    

注意事项

  1. 在Python 2中,print是语句而非函数
  2. 大量输出时可能会影响性能,考虑使用日志模块
  3. 在Jupyter Notebook等环境中,print输出可能显示在不同位置

print()函数虽然简单,但通过合理使用其参数可以实现丰富的输出效果,是Python编程中不可或缺的工具。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP