Tutorial Study Image

Python print()

print() 函数有助于将给定消息打印到屏幕或其他标准输出设备。在写入输出屏幕之前,对象将被转换为字符串。


print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) #where objects can be string,or any object
 

print() 参数

它可能包含五个参数。除了第一个参数对象外,* 表示它可能有多个。这里的 sep、end、file 和 flush 都是关键字参数。

参数 描述 必需/可选
对象  要打印的对象 必需
sep  对象由 sep 分隔。默认值:' ' 可选
结束 (end) end 最后打印 可选
file 必须是具有 write(string) 方法的对象 可选
flush  如果为 True,则强制刷新流。默认值:False 可选

print() 返回值

它不返回任何值;返回 None。

 

Python 中 print() 方法的示例

示例 1:print() 在 Python 中如何工作?


print("Python is fun.")

a = 5
# Two objects are passed
print("a =", a)

b = a
# Three objects are passed
print('a =', a, '= b')
 

输出

Python is fun.
a = 5
a = 5 = b

 

注意

1.' ' 分隔符被使用。注意,输出中两个对象之间的空格。 
2.end 参数 '\n'(换行符)被使用。
3.file 是 sys.stdout。输出打印在屏幕上。
4.flush 为 False。流未强制刷新。

 

 

示例 2:带分隔符和结束参数的 print()


a = 5
print("a =", a, sep='00000', end='\\n\\n\\n')
print("a =", a, sep='0', end='')
 

输出

a =000005


a =05

示例 3:带文件参数的 print()


sourceFile = open('python.txt', 'w')
print('Pretty cool, huh!', file = sourceFile)
sourceFile.close()
 

输出

Here first it treies to open or create python.txt.The string object 'Pretty cool, huh!' is printed to python.txt file