• 内置函数


    Pyrhon内置函数

    1.字符串类执行代码

    eval()

    print(eval("2+2")) # 4
    n = 8
    print(eval("2+n")) # 10
    def func():
        print(666)
    eval("func()") # 666
    

    exce()

    exec("""
    for i in range(10):
    print(i)
    """)
    exec("""
    def func():
        print("我是周杰伦")
    func()
    """)
    

     compile()将字符串的代码编译,代码对象能通过exec()语句来执行或者通过eval()语句进行求值

    '''
    参数说明:
    1. resource 要执⾏行行的代码, 动态代码⽚片段
    2. 文件名, 代码存放的文件名, 当传入了了第一个参数的时候, 这个参数给空就可以了了
    3. 模式, 取值有3个,
    1. exec: 一般放一些流程语句句的时候
    2. eval: resource只存放一个求值表达式.
    3. single: resource存放的代码有交互的时候. mode应为single
    '''
    code1 = "for i in range(10): print(i)"
    c1 = compile(code1, "", mode="exec")
    exec(c1)
    code2 = "1+2+3"
    c2 = compile(code2, "", mode="eval")
    a = eval(c2)
    print(a)
    code3 = "name = input('请输入你的名字:')"
    c3 = compile(code3, "", mode="single")
    exec(c3)
    print(name)
    

    有返回值的字符串串形式的代码用eval(). 没有返回值的字符串串形式的代码用exec(). 

    输入输出相关

    input()

    print()

    内存相关

    hash()

    id()

    文件操作相关

    open()

    模块相关

    __import__() 用于动态加载类和函数

    callable()用于检查一个对象是否可以调用

    dir()查看对象的内置属性

    bin() 将给的参数转换成2进制

    otc()转换八进制

    hex()转换十六进制

    divmode() 返回商和余数

    round() 四舍五入

    pow(a,b)求a的b次幂

    # 字符串串
    print(format('test', '<20')) # 左对⻬齐
    print(format('test', '>20')) # 右对⻬齐
    print(format('test', '^20')) # 居中
    # 数值
    print(format(3, 'b')) # ⼆二进制
    print(format(97, 'c')) # 转换成unicode字符
    print(format(11, 'd')) # ⼗十进制
    print(format(11, 'o')) # ⼋八进制
    print(format(11, 'x')) # ⼗十六进制(⼩小写字⺟母)
    print(format(11, 'X')) # ⼗十六进制(⼤大写字⺟母)
    print(format(11, 'n')) # 和d⼀一样
    print(format(11)) # 和d⼀一样
    # 浮点数
    print(format(123456789, 'e')) # 科学计数法. 默认保留留6位⼩小数
    print(format(123456789, '0.2e')) # 科学计数法. 保留留2位⼩小数(⼩小写)
    print(format(123456789, '0.2E')) # 科学计数法. 保留留2位⼩小数(⼤大写)
    print(format(1.23456789, 'f')) # 小数点计数法. 保留留6位⼩小数
    print(format(1.23456789, '0.2f')) # 小数点计数法. 保留留2位⼩小数
    print(format(1.23456789, '0.10f')) # 小数点计数法. 保留留10位⼩小数
    print(format(1.23456789e+10000, 'F')) # 小数点计数法.
    

      

  • 相关阅读:
    Python-异常处理机制
    递归函数——斐波那契数列j
    函数及相关操作
    字符串及相关操作
    集合及相关操作
    元组
    字典
    列表元素增删改排操作
    multiprocessing模块简单应用
    02 for循环创建进程
  • 原文地址:https://www.cnblogs.com/wszxdzd/p/9338477.html
Copyright © 2020-2023  润新知