0%

Python基础

函数

Python内置函数

参考资料:https://www.runoob.com/python/python-built-in-functions.html

截止到Python 3.6.2,python一共提供了68个内置函数,具体如下

abs() dict() help() min() setattr() all() dir() hex()
next() slice() any() divmod() id() object() sorted() ascii()
enumerate() input() oct() staticmethod() bin() eval() int() open()
str() bool() exec() isinstance() ord() sum() bytearray() filter()
issubclass() pow() super() bytes() float() iter() print() tuple()
callable() format() len() property() type() chr() frozenset() list()
range() vars() classmethod() getattr() locals() repr() zip() compile()
globals() map() reversed() __import__() complex() hasattr() max() round()
delattr() hash() memoryview() set()

和数字相关的函数

  • 1 数据类型

    bool():布尔型

    int():整型

    float():浮点型

    complex():浮点型

  • 2 进制转换

    bin():将所给参数转换为二进制

    oct():将所给参数转换为八进制

    hex():将所给参数转换为十六进制

    1
    2
    3
    print(bin(10)) # 二进制 0b1010
    print(oct(10)) # 八进制 0o12
    print(hex(10)) # 十六进制 0xa
  • 3 数学运算

    abs():计算绝对值

    1
    2
    >>> abs(-2)
    2

    divmode(a, b):计算a除以b的商和余数

    1
    2
    >>> divmod(7, 3)
    (2, 1)

    round():四舍五入

    1
    2
    >>> round(3.1415926)
    3

    pow(a, b):计算a的b次幂

    1
    2
    3
    4
    >>> pow(2, 4)
    16
    >>> pow(2, 4, 3) # 如果给了第3个参数,表示幂的计算结果取余数
    1

    sum():求和

    1
    2
    >>> sum([1, 2, 3, 4, 5])
    15

    min():求最小值

    1
    2
    >>> min(9, 7, 5, 3, 1)
    1

    max():求最大值

    1
    2
    >>> max(9, 7, 5, 3, 1)
    9

和数据结构相关的函数

  • 1 序列

  • 2 数据集合

  • 3 相关内置函数

    3.1 len() 返回一个对象中元素的个数

    1
    2
    >>> len((1, 2, 3, 4, 5))
    5

    3.2 sort() 对可迭代对象进行排序操作(lamda)

    1
    2
    3
    4
    5
    6
    lst = [5, 7, 6, 12, 1, 13, 9, 18, 5]
    lst.sort() # sort是list里面的一个方法
    print(lst)

    >>> 程序运行结果
    [1, 5, 5, 6, 7, 9, 12, 13, 18]

和作用域相关

和迭代器生成器相关

字符串类型代码的执行

输入输出

  • 1 打印输出

    1
    2
    3
    # sep:打印出的字符串之间用什么连接,end:以什么为结尾
    >>> print("Hello", "world!", "I", "come", "from", "Mars", sep="·", end="^M\n")
    Hello·world!·I·come·from·Mars^M
  • 2 获取用户输入

    1
    2
    3
    4
    5
    6
    7
    8
    a = input("Please input: ")
    print(type(a))
    print(a)

    >>> 程序运行结果
    Please input: Hello
    <class 'str'>
    Hello

内存相关

文件操作相关

模块相关

帮助

调用相关

查看内置属性

常用库

binascii

  • 该模块主要用于二进制和ASCII码之间的互相转换;
  • 包含的主要函数
函数 描述
b2a_hex(data) 返回二进制数据的16进制的表现形式
a2b_hex(data) 返回16进制数据的二进制的表现形式
  • 使用示例
解码和编码
1
2
3
4
5
6
7
8
9
>>> str = "Hello World!"
>>> hex_data = binascii.b2a_hex(str.encode())
>>> hex_str = hex_data.decode()
>>> hex_str
'48656c6c6f20576f726c6421'

>>> output_str = binascii.a2b_hex(hex_str).decode()
>>> output_str
'Hello World!'