温馨提示×

Python中print的用法有哪些

小樊
82
2024-08-29 06:35:25
栏目: 编程语言

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()函数的一些基本用法。通过组合不同的参数和格式化方法,可以实现更复杂的输出需求。

0