n [1]: dir(__builtins__)
Out[1]:
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
'BytesWarning',
'ChildProcessError',
'ConnectionAbortedError',
'ConnectionError',
'ConnectionRefusedError',
'ConnectionResetError',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EnvironmentError',
'Exception',
'False',
'FileExistsError',
'FileNotFoundError',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'InterruptedError',
'IsADirectoryError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'ModuleNotFoundError',
'NameError',
'None',
'NotADirectoryError',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'PermissionError',
'ProcessLookupError',
'RecursionError',
'ReferenceError',
'ResourceWarning',
'RuntimeError',
'RuntimeWarning',
'StopAsyncIteration',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'TimeoutError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'ZeroDivisionError',
'__IPYTHON__',
'__build_class__',
'__debug__',
'__doc__',
'__import__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'abs',
'all',
'any',
'ascii',
'bin',
'bool',
'breakpoint',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'display',
'divmod',
'enumerate',
'eval',
'exec',
'filter',
'float',
'format',
'frozenset',
'get_ipython',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'isinstance',
'issubclass',
'iter',
'len',
'license',
'list',
'locals',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'range',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']
内置常量变量查询dir(__builtins__)
"""
输出语句:
print
一、内置常量和变量的查询
dir(__builtins__)
二、str(对象)将对象转化为字符串
三、repr(对象)将对象转化为字符串,字符串表达式,是什么表达式就带什么格式符号,比如列表、元组、字典等等
输出结果带单引号
print(repr('hello, world'))
'hello, world'
四、zfill零填充输出,在数字左边填充0
流水号:0001、0002、0003、...
五、format格式化(最常用)
1.位置参数输出
2.关键字参数输出
3.位置和关键字参数混合输出
4.!a => ascii、!s => str()、!r => repr(),用于在格式化某个值之前对其进行转化
5.保留n位小数
六、旧版字符串格式化,python2
"""
输出字符,左/右 填充空格
# 9-1.将字符靠右,左边填充空格,rjust=>right
for v in range(1, 11):
print(repr(v).rjust(2), repr(v * v).rjust(3), repr(v * v * v).rjust(4))
# 9-2.将字符靠左,右边填充空格,ljust=>left
for v in range(1, 11):
print(repr(v).ljust(2), repr(v * v).ljust(3), repr(v * v * v).ljust(4))
# 9-3.将字符居中,两边填充空格,center
for v in range(1, 11):
print(repr(v).center(2), repr(v * v).center(3), repr(v * v * v).center(4))
输出对齐/左or右填充空格填充
四、zfill零填充输出,在数字左边填充0
零填充5位,包含小数点
print('3.14'.zfill(5)) # 03.14
# 11.零填充7位,包含小数点
print('3.14'.zfill(7)) # 0003.14
# 12.零填充7位,包含小数点、包含符号、符号在最左边
print('-3.14'.zfill(7)) # 00-3.14? -003.14
# 13.零填充7位
print('3.14159'.zfill(7)) # 3.14159
零填充数字串
五、字符串的格式化输出
位置参数输出
# a b c d
print("a", "b", "c", "d")
# a#b#c#d
print("a", "#", "b", "#", "c", "#", "d", sep="")
# 使用{}做为槽,占位符
print("{}#{}#{}#{}".format("a", "b", "c", "d"))
print("{0}#{1}#{2}#{3}".format("a", "b", "c", "d"))
# d#a#c#b
print("{3}#{0}#{2}#{1}".format("a", "b", "c", "d"))
"""
位置参数索引原理
索引 0 1 2 3
字符 a b c d
占位 {3} {0} {2} {1}
替换 d a c b
"""
# format格式化输出1~100的平方立方表
for v in range(1, 11):
print("{0:2d} {1:3d} {2:4d}".format(v, v ** 2, v ** 3))
使用位置参数 定义输出组合内容
format格式化输出1~100的平方立方表
for v in range(1, 11):
print("{0:2d} {1:3d} {2:4d}".format(v, v ** 2, v ** 3))
'''
结果
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
'''
使用format格式化输出& 右对齐空格占位
关键字参数输出
# 姓名:张三,年龄:18,性别:男,爱好:打篮球。
person = {"name": "张三", "age": 18, "sex": "男", "hobby": "打篮球"}
print("姓名:{},年龄:{},性别:{},爱好:{}。".format(person["name"], person["age"], person["sex"], person["hobby"]))
print("姓名:{name},年龄:{age},性别:{sex},爱好:{hobby}。".format(**person))
print("姓名:{name},年龄:{age},性别:{sex},爱好:{hobby}。".format(name="张三", age=18, sex="男", hobby="打篮球"))
# 16.位置和关键字参数混合输出,*规则:位置参数在前、关键字参数在后
# SyntaxError: positional argument follows keyword argument
# 语法错误:位置参数跟在了关键字参数的后面
print("{1} {0} {b} {a}".format(100, 99, a="python", b="study"))
# 17.!a => ascii、!s => str()、!r => repr(),用于在格式化某个值之前对其进行转化
print("{!a} {!s} {!r}".format("学习Python", "学习Python", "学习Python"))
字符串关键字参数输出
六、保留N位小数
保留n位小数
# 圆周率,保留3位小数
print(math.pi)
print("{0:.2f}".format(math.pi))
print("{0:.3f}".format(math.pi))
print("{0:.4f}".format(math.pi))
# 19.旧版字符串格式化
print("圆周率:%.3f" % math.pi)
print("圆周率:%7.3f" % math.pi)
print("姓名:%s,年龄:%d" % ("张三", 16))
保留n位小数,输入需要为数字类型