Python打印()函数
Pythonprint()函数顾名思义用于打印在Python Python对象(一个或多个)作为标准输出。
Syntax: print(object(s), sep, end, file, flush)
Parameters:
- Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into strings.
- sep: It is an optional parameter used to define the separation among different objects to be printed. By default an empty string(“”) is used as a separator.
- end: It is an optional parameter used to set the string that is to be printed at the end. The default value for this is set as line feed(“\n”).
- file: It is an optional parameter used when writing on or over a file. By default,, it is set to produce standard output as part of sys.stdout.
- flush: It is an optional boolean parameter to set either a flushed or buffered output. If set True, it takes flushed else it takes buffered. By default, it is set to False.
示例 1:打印Python对象
Python3
# sample python objetcs
list = [1,2,3]
tuple = ("A","B")
string = "Geeksforgeeks"
# printing the objects
print(list,tuple,string)
Python3
# sample python objetcs
list = [1,2,3]
tuple = ("A","B")
string = "Geeksforgeeks"
# printing the objects
print(list,tuple,string, sep="<<..>>")
Python3
# sample python objetcs
list = [1,2,3]
tuple = ("A","B")
string = "Geeksforgeeks"
# printing the objects
print(list,tuple,string, end="<<..>>")
Python3
# open and read the file
my_file = open("geeksforgeeks.txt","r")
# print the contentts of the file
print(my_file.read())
Python3
# Python code for printing to stderr
# importing the package
# for sys.stderr
import sys
# variables
Company = "Geeksofrgeeks.org"
Location = "Noida"
Email = "contact@geeksforgeeks.org"
# print to stderr
print(Company, Location, Email, file=sys.stderr)
输出:
[1, 2, 3] ('A', 'B') Geeksforgeeks
示例 2:使用分隔符打印对象
蟒蛇3
# sample python objetcs
list = [1,2,3]
tuple = ("A","B")
string = "Geeksforgeeks"
# printing the objects
print(list,tuple,string, sep="<<..>>")
输出:
[1, 2, 3]<<..>>('A', 'B')<<..>>Geeksforgeeks
示例 3:指定要在末尾打印的字符串
蟒蛇3
# sample python objetcs
list = [1,2,3]
tuple = ("A","B")
string = "Geeksforgeeks"
# printing the objects
print(list,tuple,string, end="<<..>>")
输出:
[1, 2, 3] ('A', 'B') Geeksforgeeks<<..>>
示例 4:打印和读取外部文件的内容
为此,我们还将使用Python open()函数,然后打印其内容。我们已经在系统中保存了以下名为geeksforgeeks.txt 的文本文件。
要阅读和打印此内容,我们将使用以下代码:
蟒蛇3
# open and read the file
my_file = open("geeksforgeeks.txt","r")
# print the contentts of the file
print(my_file.read())
输出:
示例 5:打印到 sys.stderr
蟒蛇3
# Python code for printing to stderr
# importing the package
# for sys.stderr
import sys
# variables
Company = "Geeksofrgeeks.org"
Location = "Noida"
Email = "contact@geeksforgeeks.org"
# print to stderr
print(Company, Location, Email, file=sys.stderr)
输出:
Geeksofrgeeks.org Noida contact@geeksforgeeks.org