首页 python基础教程 Python print()函数和format()格式化输出方法
pay pay
教程目录

Python print()函数和format()格式化输出方法

日期: 二月 13, 2023, 5:13 a.m.
栏目: python基础教程
阅读: 1316
作者: Python自学网-村长

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

我们在之前的文章中我们用的最多的就是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自学网

最后再来讲一下格式化输出format()函数用法。

a = 3
c = 'python自学网'
e = 'python'
f = 800
print('网站名称:%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()函数还能传入文件对象,这里就不多做演示了,在后面的文件读写中我们来洗洗品尝。

部分文字内容为【Python自学网】原创作品,转载请注明出处!视频内容已申请版权,切勿转载!
没有了
回顶部