Python内置方法1

来源:互联网 发布:广州易娱网络怎么样 编辑:程序博客网 时间:2024/05/19 01:09

官方实例:

https://docs.python.org/3/library/functions.html?highlight=bulit

print(all([0,-1,1]))#元素一假则假print(any([0,-1,1]))#元素一真则真
结果为:

False
True

a=ascii([1,2,'开外挂'])print(type(a),[a])
<class 'str'> ["[1, 2, '\\u5f00\\u5916\\u6302']"]
注意到print会剥离str的引号

>>> bin(1)
'0b1'
>>> bin(255)
'0b11111111'

可以判断真假,元素的有无

>>> bool(-1)
True
>>> bool(0)
False
>>> bool([1,2])
True
>>> bool([])
False

a= bytes('abcde',encoding='utf-8')print(a.capitalize(),a) #字节也是不可变类型,所以会生成副本b= bytearray('abcde',encoding='utf-8')print(b[0])#打印对应元素的ASCII码b[0]=50print(b[0])#bytearray是可变类型
b'Abcde' b'abcde'
97
50

def func():passprint(callable(func))   #callable()判断是否可以调用,可以加括号的就可以调用print(callable([]))
True
False

>>> chr(97)将ASCII转换为字符
'a'

>>> ord('a')将字符转换为ASCII
97

>>> code = 'for i in range(3): print(i)'
>>> compile(code, '','exec')
<code object <module> at 0x000001BD7DE31F60, file "", line 1>

>>> c=compile(code,'','exec')
>>> exec(c)
0
1
2

>>> exec(code)
0
1
2

>>> a='1+2*3'
>>> b=compile(a,'','eval')

>>> eval(b)
7
>>> eval(a)
7

code='''def fib(max): #生成器    n ,a ,b = 0,0,1 #这是一种tuple赋值方式    while n<max :        #print(b)        yield b #有点return的味道,        a ,b = b ,a+b #(a,b)=====(b,a+b)        n+=1    return '---done---'g=fib(6)while True:    try:        x=next(g)        print('g:',x)    except StopIteration as e:        print('generator return value:',e.value)        break'''py_obj=compile(code,'err.log','exec')exec(code)#或者exec(py_obj)
从而实现动态导入。

dir()   # show the names in the module namespace可以查看类型的方法~.>>> divmod(5,3)(1, 2)>>> divmod(5,2)(2, 1)>>> divmod(5,1)(5, 0)             得到商和余数>>> x=1>>> eval('x+1')2>>> a='"love"'      去掉一层引号>>> eval(a)'love'

原创粉丝点击