📜  python print 函数 - Python (1)

📅  最后修改于: 2023-12-03 14:46:03.105000             🧑  作者: Mango

Python print函数

在Python中,print()函数是一种常见的输出方式,用于向控制台输出指定的字符串或值。本文将为程序员介绍Python print函数的基本用法和一些高级用法。

基本用法

print函数的基本语法如下所示:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

其中,*objects代表需要输出的对象,可以是一个或多个。sep参数用于分隔多个对象,默认为一个空格。end参数用于指定输出完成后的字符串,默认为一个换行符。

以下是一些基本用法的例子:

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

name = "John"
age = 25
print("My name is", name, "and I am", age, "years old.")
# 输出:My name is John and I am 25 years old.

print("apple", "banana", "orange", sep=" | ")
# 输出:apple | banana | orange
高级用法
格式化输出

Print函数可以通过传递参数进行格式化输出。这可以通过在输出字符串中的花括号中包含参数名称和类型实现。以下是一些例子:

name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# 输出:My name is John and I am 25 years old.

print("I like {0} and {1}.".format("apples", "bananas"))
# 输出:I like apples and bananas.

print("I have {num} cats.".format(num=3))
# 输出:I have 3 cats.
使用转义字符和原始字符串

在输出字符串时,可以使用转义字符以及在字符串前加上r表示原始字符串。

print("This is the first line.\nThis is the second line.")
# 输出:
# This is the first line.
# This is the second line.

print(r"C:\Python\Programs")
# 输出:C:\Python\Programs
输出到文件

如果需要将输出内容保存到文件中而非输出到控制台,则可以通过指定file参数将输出写入到一个已打开的文本文件中。

with open("output.txt", "w") as f:
    print("Hello, World!", file=f)  
小结

Python print函数是Python中常用的一种输出方式。除了基本的输出用法外,还可以通过格式化输出实现更加灵活的输出,也可以将输出写入到文件中。