欢迎访问宙启技术站
智能推送

Python中的内置函数- print()

发布时间:2023-06-04 21:06:33

Python中的print()函数是一种非常重要的内置函数。它用于输出文本和变量值,在Python中执行输出非常常见。我们可以用print()函数来查看中间计算结果或程序的输出结果。

使用print()函数的基本语法如下:

print([object(s)], sep=’ ‘, end=’

’, file=sys.stdout, flush=False)

其中,object(s)表示要输出的一个或多个对象,多个对象用逗号隔开。sep、end、file和flush是可选参数,下面将进行说明。

(1) sep参数

sep参数是分隔符的意思。当我们向函数传递多个参数时,如果没有指定分隔符,Python默认以空格作为分隔符分隔对象。如果我们想以其他符号分隔输出对象,可以使用sep参数,如下所示:

print('a', 'b', 'c', sep='+') # 输出结果为:a+b+c

(2) end参数

end参数是表示输出后结尾的字符,默认为一个换行符。如果我们希望去掉结尾的换行符,可以使用end参数,如下所示:

print('Hello World!', end='') # 输出结果为:Hello World!

(3) file参数

file参数用于输出到指定文件。例如,如果我们想将程序的输出结果保存到一个文件中,可以使用file参数。

with open('test.txt', 'w') as f:

    print('Hello World!', file=f)

(4) flush参数

flush参数指定是否将缓冲区内容刷新到硬盘上。这个参数默认为False,表示不刷新。如果设置成True,则输出内容会及时刷新到硬盘。

print("Hello World!", flush=True)

除了以上四个参数外,print()函数还有很多用法。下面我们来介绍print()函数的一些常见用法:

1. 输出变量

我们可以使用print()函数输出变量的值。例如:

name = 'John'

print('My name is', name) # 输出结果为:My name is John

2. 输出数据类型

我们可以使用print()函数输出变量的数据类型。Python提供了内置函数type()来获取对象的数据类型。例如:

a = 1

print(type(a)) # 输出结果为:<class 'int'>

3. 格式化输出

如果我们想更加精确的控制输出结果的格式,可以使用格式化输出。Python提供了多种格式化输出方式,常见的有%s,%d,%f等,例如:

name = 'John'

age = 18

print('My name is %s and I am %d years old.' % (name, age)) # 输出结果为:My name is John and I am 18 years old.

4. 输出特定字符数

我们可以使用print()函数的切片功能来输出指定字符数的内容。例如:

line = 'Python is a high-level interpreted programming language.'

print(line[:10]) # 输出结果为:Python is

5. 输出列表或元组

我们可以使用print()函数输出列表或元组的内容。例如:

my_list = [1, 2, 3, 4]

print(my_list) # 输出结果为:[1, 2, 3, 4]

my_tuple = (5, 6, 7, 8)

print(my_tuple) # 输出结果为:(5, 6, 7, 8)

6. 输出字典

我们可以使用print()函数输出字典的内容。例如:

my_dict = {'Name': 'John', 'Age': 18, 'Gender': 'Male'}

print(my_dict) # 输出结果为:{'Name': 'John', 'Age': 18, 'Gender': 'Male'}

7. 输出多行字符串

我们可以使用三个引号来输出多行字符串。例如:

print('''Mary had a little lamb,

Its fleece was white as snow,

And everywhere that Mary went,

The lamb was sure to go.''') 

# 输出结果为:

# Mary had a little lamb,

# Its fleece was white as snow,

# And everywhere that Mary went,

# The lamb was sure to go.

总结:

print()函数是Python中最基本的输出函数之一,非常常用。它不仅可以输出简单的字符串和变量值,还可以输出数据类型、格式化输出、输出特定字符数、输出列表、元组和字典等功能。掌握print()函数的使用方法,是Python编程的基础之一。