在 Python 中,在 2.x 版本中,
print参数选项
用 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: 是否强制刷新到输出流,默认否
python字符串格式化符号:
| 符 号 | 描述 |
|---|---|
| %c | 格式化字符及其ASCII码 |
| %s | 格式化字符串 |
| %d | 格式化整数 |
| %u | 格式化无符号整型 |
| %o | 格式化无符号八进制数 |
| %x | 格式化无符号十六进制数 |
| %X | 格式化无符号十六进制数(大写) |
| %f | 格式化浮点数字,可指定小数点后的精度 |
| %e | 用科学计数法格式化浮点数 |
| %E | 作用同%e,用科学计数法格式化浮点数 |
| %g | %f和%e的简写 |
| %G | %f 和 %E 的简写 |
| %p | 用十六进制数格式化变量的地址 |
打印任意数据
- 打印数字、字符串、布尔值
print(1024, 10.24, 'hello', False)
# 1024 10.24 hello False- 打印列表
print([1, 2, 3])
# [1, 2, 3]- 打印元组
print((1, 2, 3))
# (1, 2, 3)- 打印字典
print({'name': 'hello', 'age': 18})
# {'name': 'hello', 'age': 18}- 打印集合
print({1, 2, 3})
# {1, 2, 3}- 打印对象
class Demo:
pass
demo = Demo()
print(demo)
# <__main__.Demo object at 0x1005bae80>分隔符
默认分隔符是空格,sep 参数可以修改。
print(1, 2, 3, sep='-')
# 1-2-3结束符
默认结束符是行号,end 参数可以修改。
print('第一行', end='-')
print('第二行')
# 第一行-第二行输出重定向
默认情况下,print 函数会将内容打印输出到标准输出流(即 sys.stdout),可以通过 file 参数自定义输出流。
with open('data.log', 'w') as fileObj:
print('hello world!', file=fileObj)此时,不会有任何标准输出,但对应的文件中已经有了内容。
我们也可以输出到错误输出流,例如:
import sys
print('hello world!', file=sys.stderr)
评论列表(0条)