跳至主要内容

Python Print() 函数

通过示例学习如何以多种方式充分利用简单的 Python Print 函数的能力。
· 10分钟 阅读

使用 AI 探索

如果您刚开始学习 Python 并希望了解更多,欢迎参加 DataCamp 的Python 中的数据科学入门课程。

banner

许多读者在阅读本教程时,可能会觉得对于一个简单的Python Print 函数并没有什么可挖掘的,毕竟大家学习 Python 时几乎都是从打印 Hello, World! 这个万年经典示例开始的。确实,不论是 Python 还是其他任何编程语言,Print 函数都是入门时的最基础“第一步”。不过,在学习一门语言的过程中,您有时会更关注高级主题,而忽略了那些几乎时时在用的简单函数的细节与能力。

本教程将把重点完全放在 Python 的 Print 函数上;您将了解这个最容易被低估的函数。

让我们先用 Hello, World! 例子开个头。

print("Hello, World!")
Hello, World!

与不要求加括号的 Python2 不同,在 Python3 中必须加上括号,否则会抛出语法错误,如下所示。

print "Hello, World!"
  File "<ipython-input-6-a1fcabcd869c>", line 1
    print "Hello, World!"
                        ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello, World!")?

从上面的输出可以得出结论:在 Python3 中,print() 不是语句而是函数。

既然如此,让我们来查看一下 print() 函数的 type/class。

type(print)
builtin_function_or_method

它返回 builtin_function_or_method,这意味着它是一个预定义的内置Python 函数。

现在假设您想在下面两行输出之间添加一个新行或垂直空白,为此可以直接调用一次不带任何参数的 print() 函数。

print("Hello, World!");print("Hello, World!")
Hello, World!
Hello, World!
print("Hello, World!")
print()
print("Hello, World!")
Hello, World!

Hello, World!

来看一下 print() 函数的语法。print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) 如您所知,print 函数会将值打印到某个流,默认是 sys.stdout。sys.stdout 或系统标准输出意味着 print 函数会将结果输出到屏幕,当然也可以改为 stdin 或 stderr。

可选关键字参数:

  • sep:您希望插入在各个值之间的字符串,默认为空格。

    让我们把一组单词放进 print 函数,并用换行将它们分隔。请记住,默认情况下分隔符会在每个单词之间添加一个空格。

print('datacamp','tutorial','on','python','print','function')
datacamp tutorial on python print function
print('datacamp','tutorial','on','python','print','function',sep='\n') #`\n` will put each word in a new line
datacamp
tutorial
on
python
print
function

同样,您也可以用逗号分隔,或者加两个 \n 来在中间增加一行空白,甚至加入加号 $(+)$ 符号。

print('datacamp','tutorial','on','python','print','function',sep=',')
datacamp,tutorial,on,python,print,function
print('datacamp','tutorial','on','python','print','function',sep='\n\n')
datacamp

tutorial

on

python

print

function
print('datacamp','tutorial','on','python','print','function',sep=',+')
datacamp,+tutorial,+on,+python,+print,+function

在继续下一个参数 end 之前,请记住您也可以把变量传给 print 函数。为了解释这一点,下面定义一个整数列表并传给 print 函数。您会期望它打印出这个整数列表。

int_list = [1,2,3,4,5,6]
print(int_list)
[1, 2, 3, 4, 5, 6]
  • end:在最后一个值后追加的字符串,默认为换行。它允许程序员为每次 print 调用定义一个不同于默认换行符 \n 的结尾字符。

    假设您有两个字符串,想用空格把它们拼在一起,您只需在第一个字符串 str1 的 print 函数中添加带引号的 end 参数,就能让两个字符串以空格连接。

str1 = 'datacamp tutorial on'
str2 = 'python print function'
print(str1)
print(str2)
datacamp tutorial on
python print function
print(str1,end=' ')
print(str2)
datacamp tutorial on python print function

再看一个示例:您有一个函数,任务是在同一行打印列表中的所有值。您可以用 end 参数来实现,如下所示:

def value(items):
    for item in items:
        print(item, end=' ')
value([1,2,3,4])
1 2 3 4
  • file:类文件对象(流);默认为当前的 sys.stdout。您可以在此指定希望写入或追加 print 函数输出的文件。

    通过使用 file 参数,您可以将 print 函数的输出保存到诸如 .csv、.txt 等各种格式的文件中。以下面的例子来理解:遍历列表中的每个元素,并将其保存到一个文本文件中。为此,先以追加模式打开一个文本文件,用来保存 print 语句的输出。然后定义函数,其输出会被追加到该文本文件。

file = open('print.txt','a+')
def value(items):
    for item in items:
        print(item, file=file)
    file.close() # close the file ones the function execution completes.
value([1,2,3,4,5,6,7,8,9,10])

上述函数执行完成后,您应能在当前目录看到一个名为 print.txt 的文件。我们打开看看其内容。

output

从上面的输出可以清楚地看到,您不仅可以在终端或笔记本中打印输出,还可以将输出保存到文件。

  • flush:决定是否强制刷新流。默认值为 False。

    通常,输出到文件或控制台会被缓冲,至少会在您打印一个换行符之前进行缓冲(来源)。缓冲意味着输出会被存放在某种寄存器中,待准备就绪或文件最终关闭后再写入。flush 的作用是确保被缓冲的输出安全地发送到目标位置。

import time
print('Please enter your email-id : ', end=' ')
#print('Please enter your email-id : ', end=' ', flush=True) #run this to see the difference and comment out the above line of code.
time.sleep(5)
Please enter your email-id :  

如果您在终端运行上述代码,会注意到提示字符串在休眠计时结束、程序退出之前不会显示(来源)。然而,如果在 print 函数中添加 flush=True,您会先看到提示,然后需要等待 5 秒钟程序才结束。

Jupyter Notebook 或 Jupyter Lab 在这方面会有所处理,能在 5 秒计时之前显示提示。因此,如果您想测试 print 的此项功能,请务必在命令行终端中运行,而不要在 jupyter notebook 中运行。

现在看看如何在 jupyter notebook 中结合 print 函数从用户处获取输入。为此,您将使用 Python 的内置函数 input()。

tutorial_topic = input()
print("The topic of today's tutorial is: ", end='')
print(tutorial_topic)
 Print Function


The topic of today's tutorial is: Print Function

一旦运行上述单元格,您将看到如下输出:

output

此处您定义了之前学过的可选命名参数 end,它用于将 print 语句中的固定文本与用户输入进行拼接。

接下来看看一些更“酷”的方式,在 print 函数内打印变量的值。

  • 若要在预定义字符串中显示变量的值,您只需在两者之间加一个逗号。此时预定义字符串和变量的位置并不重要。
a = 2
b = "Datacamp"
print(a,"is an integer while",b,"is a string.")
2 is an integer while Datacamp is a string.
  • 您可以使用 format 参数,在其中传入任意多个要打印的变量。当您把变量传给 format 函数时,需要在预定义字符串中指定索引号(即它们在 format 参数中的位置顺序)。这样,这个 print 函数就会充当一个模板。

    还需要记住的一点是,这里的索引号用花括号 {} 表示占位符。

    看下面的示例:

a = 2
b = "Datacamp"
print("{0} is an integer while {1} is a string.".format(a,b))
2 is an integer while Datacamp is a string.

如果把第二个变量的索引号放在两个位置,那么如预期那样,它会打印相同的值,在这里就是变量 b 在两处都被使用。

print("{1} is an integer while {1} is a string.".format(a,b))
Datacamp is an integer while Datacamp is a string.
  • 与 format 参数让 print 函数充当模板类似,您也可以使用百分号(%)来打印变量的值。

    与 format 参数一样,这种方式也有占位符的概念。不过,不同于 format 函数只传入索引号,这里还需要为占位符指定期望的数据类型。

    • %d 用作数字或十进制值的占位符。
    • %s 用作字符串的占位符。
a = 2
b = "Datacamp"
print("%d is an integer while %s is a string."%(a,b))
2 is an integer while Datacamp is a string.

看看如果为整数变量 a 使用 %s 会发生什么。

print("%s is an integer while %s is a string."%(a,b))
2 is an integer while Datacamp is a string.

如上例所示,它依然可以工作。原因在于 Print 函数隐式地进行了类型转换,把整数转换成了字符串。不过,反过来却不成立。它无法将字符串转换为整数,会导致 TypeError。

我们来验证一下。

print("%d is an integer while %d is a string."%(a,b))
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-121-68c55041ecfe> in <module>
----> 1 print("%d is an integer while %d is a string."%(a,b))


TypeError: %d format: a number is required, not str

结论

恭喜您完成本教程。

本教程是初学者迈向精通 Python 的良好起点。您可能还想继续多多尝试 Print 函数,探索一些本教程未涉及的功能。

如对本教程有任何问题,欢迎在下方评论区留言。

如果您刚开始学习 Python 并希望了解更多,请查看 DataCamp 的Python 中的数据科学入门课程以及Python 函数教程。

主题