python骚操作---Print函数用法

---恢复内容开始---

python骚操作---Print函数用法

在 Python 中,print 可以打印所有变量数据,包括自定义类型。

在 3.x 中是个内置函数,并且拥有更丰富的功能。

参数选项

可以用 help(print) 来查看 print 函数的参数解释。

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.
  • value: 打印的值,可多个
  • file: 输出流,默认是 sys.stdout
  • sep: 多个值之间的分隔符
  • end: 结束符,默认是换行符 \n
  • flush: 是否强制刷新到输出流,默认否

1. 字符串和数值类型

>>> print(1)
1
>>> print("Hello World")
Hello World

2.输出重定向 

默认情况下,print 函数会将内容打印输出到标准输出流(即 sys.stdout),可以通过 file 参数自定义输出流。 

with open('data.log', 'w') as fileObj:
  print( 'hello world!', file=fileObj)

此时,不会有任何标准输出,但对应的文件中已经有了内容。

我们也可以输出到错误输出流,例如:

import sys
print('hello world!', file=sys.stderr)

3.分隔

>>>print("hello", "world", "hello", "world", "hello", "world", sep="-")
hello-world-hello-world-hello-world

4.结束符

默认结束符是行号,end 参数可以修改。 

>>>for i in range(10):
           print(">")
>>>>
>
>
>
>
>
>
>
>
>
>>>for i in range(10):
           print(">",end="")
>>>>>>>>>>>>>

5.换行

print在运行过程是,print将数据写入缓冲区,缓冲区将数据刷新到控制台显示

其中缓存区将数据刷新到控制台的条件有三个,满足其中一个就可以刷新到控制台显示

1.有换行符,

2.flush为Ture

3.代码运行结束或者缓存区满了

猜你喜欢

转载自www.cnblogs.com/f67373mama/p/11370409.html
今日推荐