Python print() 函数用法

2023-09-17 22:26:07

print() 方法将给定的对象打印到控制台或文本流文件。

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

参数:

对象
  1. :要打印的一个或多个对象,默认情况下用空格 ' ' 分隔。
  2. Sep:(可选)如果传递了多个对象,则用指定的分隔符分隔它们。默认值为" "。
  3. end:(可选)要打印的最后一个值。默认值为"\ "。
  4. 文件:(可选)必须是具有write(string)方法的对象。默认值为 sys.stdout
  5. 刷新
  6. :(可选)如果缓冲,则强制刷新流。默认值为 False。

返回值:

无返回值。

下面的示例打印各种对象。

print("Learning Python")
name = 'John'
print("My name is",name)

输出:

Learning Python
My name is John

我们可以传递各种参数来更改输出。

name = 'John'
print("My name is",name,sep='---',end = "\n\n\n\n")
print("I am 18 years old")

输出:

My name is---John
I am 18 years old

下面将对象打印到文件中。

printtofile = open('debug.txt', 'w')
print('printing to file', file = printtofile)
printtofile.close()