python内建函数

python解释器提供了70多个内置函数。

>>> import builtins
>>> print(dir(builtins))
['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']

全小写的就是全局内建函数。

基本数据类型函数

int

  • int([x]) -> integer
  • int(x, base=10) -> integer

讲一个数字或者数字字符串转换成十进制整数,如果x不是一个十进制数字,那么它必须是和进制base匹配的整数字符串表达式

>>> int(1.1)
1
>>> int('1')
1
>>> int('0b0101',2)		# 二进制
5
>>> int('0x11',16)		# 十六进制
17
>>> int('0o11',8)		# 八进制
9

float

将一个字符串或数字转换为浮点数。

>>> float(123)
123.0
>>> float('1.2')
1.2

complex

  • complex(real=0, imag=0) 创建一个复数通过实部和虚部
>>> complex(10,8)
(10+8j)

str

  • str(object='') 通过给定的对象创建一个新的字符串对象。
>>> str(1)
'1'
>>> str([1,2,3])
'[1, 2, 3]'
>>> str({'name':'xinlan'})
"{'name': 'xinlan'}"

list

  • list(iterable=())

根据传入的可迭代对象创建一个列表,如果没有参数返回空列表

>>> list()
[]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list('abcde')
['a', 'b', 'c', 'd', 'e']

tuple

  • tuple(iterable=())

根据传入的可迭代对象创建一个元组,如果没有参数返回空元组

>>> tuple()
()
>>> tuple('abcd')
('a', 'b', 'c', 'd')

set

  • set(iterable)

根据传入的可迭代对象创建一个集合对象。

>>> set('abc')
{'a', 'b', 'c'}
>>> set(range(10))
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

dict

根据传入的参数创建一个字典对象

# 形如(key, value)的键值对数据
>>> dict([('name','xinlan'),('age',18)])
{'name': 'xinlan', 'age': 18}
# 关键字参数
>>> dict(name='xinlan',age=18)
{'name': 'xinlan', 'age': 18}

常用内建函数

print

  • print(value,..,sep=' ', end='\n')
    • value 会打印value的字符串形式
    • sep 分隔符,当有多个value时默认用空格作为分割
    • end 每次打印在最后默认添加回车换行符

打印传入对象的字符串形式

>>> print(1,2,3,sep=',')		# 修改分隔符为,
1,2,3
>>> print(1,end='');print(2)			# 修改打印后添加为字符串空
12

input

接收用户的输入数据,以字符串的形式返回。

可以接收字符串参数最为提示信息输出

>>> input('>>>:')
>>>:aaa
'aaa'    

type

  • type(object)

返回object的类型

>>> type(1)
int

dir

  • dir([object])

返回传入对象的所有属性和方法名的列表

>>> print(dir(1))
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

help

  • help(builtins.object)

返回内建对象的帮助信息

>>> help(help)

len

  • len(obj)

返回容器的元素个数

>>> len([1,2,3])

hash

  • hash(obj)

返回对象的hash值

>>> hash('a')
3636161774609400683

iter

  • iter(iterable)

根据传入的可迭代对象返回一个迭代器

>>> iter('abcd')
<str_iterator at 0x7f98b7dd2eb0>

id

  • id(obj)

返回传入对象的身份id(虚拟内存地址的整数形式)

>>> id(1)
4344134656

range

  • range(stop) -> range object
  • range(start, stop[,step])

返回一个range object对象,产生整数序列

>>> range(10)
range(0, 10)
>>> range(0,10,2)
range(0, 10, 2)

更多方法详见官方文档

posted @ 2022-08-23 14:10  python心蓝  阅读(89)  评论(0编辑  收藏  举报