温馨提示×

Python中print的用法有哪些

小樊
92
2024-08-29 06:35:25
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中的print()函数是一个非常常用的内置函数,用于在控制台输出文本。以下是一些常见的print()函数用法:

  1. 基本用法:
print("Hello, World!")
  1. 输出变量:
name = "John"
age = 30
print("My name is", name, "and I am", age, "years old.")
  1. 使用格式化字符串(f-string):
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
  1. 使用format()方法进行字符串格式化:
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
  1. 使用sep参数指定分隔符:
print("apple", "banana", "cherry", sep=", ")
  1. 使用end参数指定行尾字符:
print("Hello, World!", end="\n\n")
  1. 使用file参数将输出重定向到文件:
with open("output.txt", "w") as file:
    print("Hello, World!", file=file)
  1. 使用flush参数立即刷新输出缓冲区:
import time
for i in range(5):
    print(i, flush=True)
    time.sleep(1)

这些只是print()函数的一些基本用法。通过组合不同的参数和格式化方法,可以实现更复杂的输出需求。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python中print的用法是什么

0