zl程序教程

您现在的位置是:首页 >  Python

当前栏目

Prin()输出函数和使用方法

2023-03-20 14:55:59 时间

我们在之前的文章中我们用的最多的就是print()这个函数来打印一些数据,这就是我们今天要讲的输出语句,通过print()不仅可以输出变量,还有很多其他功能。下面就来详细讲解一下。

一、print()函数的构造

def print(self, *args, sep=' ', end='
', file=None): # known special case of print
 """
 print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
 Prints the values to a stream, or to sys.stdout by default.
 Optional keyword arguments:
 file:  a file-like object (stream); defaults to the current sys.stdout.
 sep:   string inserted between values, default a space.
 end:   string appended after the last value, default a newline.
 flush: whether to forcibly flush the stream.
 """
 pass

通过上面的构造函数我们可以看出来,这个函数可以传入多个值,并且自带空格隔开每个变量,另外结尾会自带一个换行。下面我们来演示一下。

a = 3
c = 'python自学网'
e = 'python'print(c*a, e)print(c)
返回结果:
python自学网python自学网python自学网 python
python自学网

大家可以看出来两行打印代码会自动换行,我们也可以通过其他方法自定义结尾的格式。

a = 3
c = 'python自学网'
e = 'python'print(c*a, e, end="")print(c)
返回结果:python自学网python自学网python自学网 pythonpython自学网

二、print()函数格式化输出

a = 3
c = 'python自学网'
e = 'python'
f = 800print('网站名称:%s' % c) 
# 使用%s来替换字符串print('网站有视频教程:%d集以上' % f) 
# 使用%d来替换数字print('{}视频教程'.format(e)) 
# 使用format()函数来替换所有字符print(c, '	', e) 
 # 	 表示空格print(c, '
', e) # 
 表示换行
返回结果:
网站名称:python自学网
网站有视频教程:800集以上
python视频教程
python自学网      python
python自学网
 python

此外print()函数还能传入文件对象,这里就不多做演示了,在后面的文件读写中我们来细细品尝。