前言
我发现,有很多人在初学时学习的函数都不完全,所以,我打算写《小函数,细细讲》,让大家对小函数有新的认知。
正文
print的位置及使用方法
from builtins import print
不得不提到的一点是,这个库无需导入,不像C++的<iostream>
@overload
def print(
*values: object,
sep: str | None = " ",
end: str | None = "\n",
file: SupportsWrite[str] | None = None,
flush: Literal[False] = False,
) -> None: ...
这下就一目了然了,我们也知道了它的构造
简单而言,就是
print("内容")
这也正是大家常写的,可接下来的内容会教你灵活运用print
基础
print() # 换行
print("Hello World!") # 普通输出
print("Hello", "World!") # 多参数
print("Hello", "World!", sep=" Python ") # 多参数+中间改变
print("Hello World!", end=" Thanks!\n") # 结尾改变
with open(r"text.txt", "w") as f:
print("Hello World!", file=f) # 文本写入(重定向输出)
print("Hello!", flush=True) # 刷新界面
不仅如此print还可以输出表达式
print(1)
var = 123456789
tup = (1, 2, 3, 4, 5, 6, 7, 8, 9)
lis = [1, 2, 3, 4, 5, 6, 7, 8, 9]
dic = {
"a": 1,
"b": 2,
"c": 3
}
print(var)
print(tup)
print(lis)
print(dic)
print(3 + 4, 3 - 4, 3 * 4, 3 / 4, 3 % 4, 3 ** 4, 3 ^ 4, 3 == 4, 3 != 4)
print(abs(-5))
除此之外,我们还可以做到合并
pi = [3, ".", 1, 4, 1, 5, 9, 2, 6]
for x in pi:
print(x, end="")
我们甚至可以做到绘图
print("\n"
" $ $ $ $ \n"
"$ $ $ $ $ $ $\n"
"$ $ $ $ $ $ $\n"
" $ $ $ $ $ \n"
" $ $ $ \n"
" $ \n")
print("\n"
" $ \n"
" $ $ $ $ $ \n"
"$ $ $\n"
"$ $ \n"
" $ $ \n"
" $ $ \n"
" $ \n"
" $ $ \n"
" $ $ \n"
" $ $\n"
"$ $ $\n"
" $ $ $ $ $ \n"
" $ \n")
高级
print("\d\s\f" %(a, b, c)) # 格式化输出
print(f"{a}{b}{c}") # f-string格式化
print("{}{}{}".format(a, b, c)) # 主角
其他的统统不用学,只需掌握format
print("...{索引}, ... , {索引}, ...".format(值1, 值2))
print("...{key1}, ... , {key2}, ...".format(key1=value,key2=value))
name='i_like_co'
age=13
print('name {},age {}'.format(name,age))
print('name {0},age {1}'.format(name,age))
print('name {name},age {age}'.format(name='xiaoming',age=12))
#输出:name i_like_co,age 13
是不是简单而功能强大?再来看看下面
# {索引:[填充字符][对齐方式][宽度]}
# *<20:左对齐,总共20个字符,不够的用*号填充
print('{0:*<20}'.format('hellopython'))
# *>20:右对齐,总共20个字符,不够的用*号填充
print('{0:*>20}'.format('hellopython'))
# *^20:居中显示,总共20个字符,不够的用*号填充
print('{0:*^20}'.format('hellopython'))
"""
输出:
hellopython*********
*********hellopython
****hellopython*****
"""
学会了吗?对齐不写填充字符就行了(用空格)
#保留2位有效数字
print("{:.2f}".format(3.1415926))
#转成二进制
print('{0:b}'.format(16))
#转成八进制
print('{0:o}'.format(10))
#转成十六进制
print('{0:x}'.format(15))
"""
输出
3.14
10000
12
f
"""
是不是比格式化输出好用的多,比 f-string强大的多?
尾声
以上关于print的用法就到这里了,谢谢观看!