【100+ python基础入门-12】print()输出函数

导读:本篇文章讲解 【100+ python基础入门-12】print()输出函数,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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

一、print()函数的构造

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print

    """

    print(value, ..., sep=' ', end='\n', 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, '\t', e)  
# \t 表示空格print(c, '\n', e)  # \n 表示换行

返回结果:

网站名称:python自学网
网站有视频教程:800集以上
python视频教程
python自学网      python
python自学网
 python

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/73461.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!