17 python 内置函数

内置函数:Python的内部自带的函数

作用域相关:

   基于字典的形式获取局部变量和全局变量

    globals()——获取全局变量的ha1 

    locals()——获取执行本方法所在命名空间内的局部变量的字典

其他函数:

  字符串类型代码的执行

    eval() 将字符串类型的代码执行并返回结果 

      
1 print(eval('1 + 2 + 3 + 4'))
View Code

    exec()将自字符串类型的代码执行

      
1 print(exec('1 + 2 + 3 + 4')) # 没有返回值
2 exec("print('hello,world')")
View Code

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

      参数说明:   

        1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  

        2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  

        3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为            ‘eval’;当source中包含了交互式命令语句,model应指定为'single'。

        流程语句使用exec

          
1 code1 = 'for i in range(0,10): print (i)'
2 
3 compile1 = compile(code1,'','exec')
4 
5 exec (compile1)
View Code

        简单求值表达式用eval

          
1 code2 = '1 + 2 + 3 + 4'
2 
3 compile2 = compile(code2,'','eval')
4 
5 eval(compile2)
View Code

        交互语句用single

          
1 code3 = 'name = input("please input your name:")' 
2 
3 compile3 = compile(code3,'','single')
4 
5 print(name)
View Code

    输入输出相关

       input() 输入

        
1 s = input("请输入内容 : ") #输入的内容赋值给s变量
2 
3 print(s) #输入什么打印什么。数据类型是str
View Code

       print() 输出     

        
 1 def print(self, *args, sep=' ', end='
', file=None): # known special case of print """
 2 
 3 print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
 4 
 5 file: 默认是输出到屏幕,如果设置为文件句柄,输出到文件
 6 
 7 sep: 打印多个值之间的分隔符,默认为空格
 8 
 9 end: 每一次打印的结尾,默认为换行符
10 
11 flush: 立即把内容输出到流文件,不作缓存 """
View Code

       open() 打开文件函数

        
1 f = open('tmp_file','w')
2 
3 print(123,456,sep=',',file = f,flush=True)
View Code

      import 关键字  引入模块

        # 进度条 

        
 1 import time
 2 
 3 for i in range(0,101,2):
 4 
 5   time.sleep(0.1)
 6 
 7   char_num = i//2 #打印多少个'*'
 8 
 9   per_str = '
%s%% : %s
' % (i, '*' * char_num) if i == 100 else '
%s%% : %s'%(i,'*'*char_num)
10 
11   print(per_str,end='', flush=True) #小越越 : 
 可以把光标移动到行首但不换行
View Code

    数据类型相关

      type(o) 返回变量o的数据类型

    内存相关

      id(o) o是参数,返回一个变量的内存地址

      hash(o) o是参数,返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错。

        hash函数会根据一个内部的算法对当前可hash变量进行处理,返回一个int数字。

        *每一次执行程序,内容相同的变量hash值在这一次执行过程中不会发生改变。   

         
1 t = (1,2,3)
2 
3 l = [1,2,3]
4 
5 print(hash(t)) #可hash
6 
7 print(hash(l)) #会报错
View Code

    文件操作相关

      open()  打开一个文件,返回一个文件操作符(文件句柄)

        操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+)  可以用encoding指定编码.

    模块操作相关

      import 关键字 导入一个模块 

      
1 import time
2 
3 os = __import__('os')
4 
5 print(os.path.abspath('.'))
View Code

    帮助方法

      在控制台执行help()进入帮助模式。可以随意输入变量或者变量的类型。输入q退出或者直接执行help(o),o是参数,查看和变量o有关的操作。。。

    调用相关

      callable(o),o是参数,看这个变量是不是可调用。如果o是一个函数名,就会返回True  

      
1 def func():pass
2 
3 print(callable(func)) #参数是函数名,可调用,返回True
4 
5 print(callable(123)) #参数是数字,不可调用,返回False
View Code

    查看参数所属类型的所有内置方法

      dir() 默认查看全局空间内的属性,也接受一个参数,查看这个参数内的方法或变量

        
1 print(dir(list)) #查看列表的内置方法
2 
3 print(dir(int)) #查看整数的内置方法
View Code

  和数字相关

    数字——数据类型相关:bool,int,float,complex

      数字——进制转换相关:bin,oct,hex

      数字——数学运算:abs,divmod,min,max,sum,round,pow

  和数据结构相关

    序列——列表和元组相关的:list和tuple

    序列——字符串相关的:str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr  

      
 1 ret = bytearray('alex',encoding='utf-8')
 2 
 3 print(id(ret))
 4 
 5 print(ret[0])
 6 
 7 
 8 ret[0] = 65
 9 
10 print(ret)
11 
12 print(id(ret))
13 
14 
15 ret = memoryview(bytes('你好',encoding='utf-8'))
16 
17 print(len(ret))
18 
19 print(bytes(ret[:3]).decode('utf-8'))
20 
21 print(bytes(ret[3:]).decode('utf-8'))
View Code

    序列:reversed,slice

      
 1 l = (1,2,23,213,5612,342,43)
 2 
 3 print(l)
 4 
 5 print(list(reversed(l)))
 6 
 7 
 8 l = (1,2,23,213,5612,342,43)
 9 
10 sli = slice(1,5,2)
11 
12 print(l[sli])
View Code

    数据集合——字典和集合:dict,set,frozenset

    数据集合:len,sorted,enumerate,all,any,zip,filter,map

      filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

        例如,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除偶数,保留奇数,首先,要编写一个判断奇数的函数:然后,利用filter()过滤掉偶数:   

          
1 def is_odd(x):
2 
3   return x % 2 == 1
4 
5 filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
6 
7 结果:[1, 7, 9, 17]
View Code

        利用filter(),可以完成很多有用的功能,例如,删除 None 或者空字符串:

          
1 def is_not_empty(s):
2 
3    return s and len(s.strip()) > 0
4 
5 filter(is_not_empty, ['test', None, '', 'str', ' ', 'END'])
6 
7 结果:['test', 'str', 'END']
View Code

        注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。当rm为空时,默认删除空白符(包括' ', ' ', ' ', ' '),如下:

          
1 a = ' 123'
2 a.strip()
3 '123'
4 
5 a = '		123
'
6 a.strip()
7 '123'
View Code

        请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

          
1 import math
2 
3 def is_sqr(x):
4 
5   return math.sqrt(x) % 1 == 0
6 
7 print filter(is_sqr, range(1, 101))
8 
9 结果:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
View Code

      map()Python中的map函数应用于每一个可迭代的项,返回的是一个结果list。如果有其他的可迭代参数传进来,map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。

        有一个list, L = [1,2,3,4,5,6,7,8],我们要将f(x)=x^2作用于这个list上,那么我们可以使用map函数处理。

          
1 L = [1,2,3,4,]
2 
3 def pow2(x):
4 
5   return x*x
6 
7 map(pow2,L)
8 
9 [1, 4, 9, 16] 
View Code

      sorted()对List、Dict进行排序,Python提供了两个方法对给定的List L进行排序,
        方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本
        方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变

        参数说明:
          iterable:是可迭代类型;
          key:传入一个函数名,函数的参数是可迭代类型中的每一项,根据函数的返回值大小排序;
          reverse:排序规则. reverse = True  降序 或者 reverse = False 升序,有默认值。
          返回值:是一个经过排序的可迭代类型,与iterable一样。

          列表按照其中每一个值的绝对值排序

            
l1 = [1,3,5,-2,-4,-6]
l2 = sorted(l1,key=abs)
print(l1)
print(l2)
View Code

           列表按照每一个元素的len排序

            
1 l = [[1,2],[3,4,5,6],(7,),'123']
2 print(sorted(l,key=len))
View Code

    

Python全栈之路系列之Python3内置函数

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.

   Built-in Functions   
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()    

官方介绍:https://docs.python.org/3/library/functions.html

abs(x)

返回数字的绝对值,参数可以是整数或浮点数,如果参数是复数,则返回其大小

    
1 # 如果参数是复数,则返回其大小。
2  >>> abs(-25)
3 25
4  >>> abs(25)
5 25
View Code

all(iterable)

all()会循环括号内的每一个元素,如果括号内的所有元素都是真的,或者如果iterable为空,则返回True,如果有一个为假的那么就返回False

    
1 >>> all([])
2 True
3 >>> all([1,2,3])
4 True
5 >>> all([1,2,""])
6 False
7 # 如果有一个为假,则都为假
8 >>> all([1,2,None])
9 False
View Code

  假的参数有:False0None""[](){}等,查看一个元素是否为假可以使用bool进行查看。

any(iterable)

循环元素,如果有一个元素为真,那么就返回True,否则就返回False

    
1  >>> any([0,1])
2 True
3  >>> any([0])
4 False
View Code

ascii(object)

在对象的类中寻找__repr__方法,获取返回值

    
1  >>> class Foo:
2  ...  def __repr_(self):
3  ...     return "hello"
4  ...
5  >>> obj = Foo()
6  >>> r = ascii(obj)
7  >>> print(r)
8 # 返回的是一个可迭代的对象
9 <__main__.Foo object at 0x000001FDEE13D320>
View Code

bin(x)

  将整数x转换为二进制字符串,如果x不为Python中int类型,x必须包含方法__index__()并且返回值为integer

    
 1 # 返回一个整数的二进制
 2  >>> bin(999)
 3 '0b1111100111'
 4 
 5 # 非整型的情况,必须包含__index__()方法切返回值为integer的类型
 6  >>> class myType:
 7  ...   def __index__(self):
 8  ...       return 35
 9  ...
10  >>> myvar = myType()
11  >>> bin(myvar)
12 '0b100011'
View Code

bool([x])

  查看一个元素的布尔值,非真即假

    
1  >>> bool(0)
2 False
3  >>> bool(1)
4 True
5  >>> bool([1])
6 True
7  >>> bool([10])
8 True
View Code

bytearray([source [, encoding [, errors]]])

返回一个byte数组,Bytearray类型是一个可变的序列,并且序列中的元素的取值范围为 [0 ,255]。 

  source参数:

  1. 如果source为整数,则返回一个长度为source的初始化数组;
  2. 如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
  3. 如果source为可迭代类型,则元素必须为[0 ,255]中的整数;
  4. 如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray.。
  1. 1  >>> bytearray(3)
    2 bytearray(b'x00x00x00')
    3 
    4 bytes([source[, encoding[, errors]]])
    5 
    6  >>> bytes("asdasd",encoding="utf-8")
    7 b'asdasd'
    View Code

callable(object)

返回一个对象是否可以被执行

    
1  >>> def func():
2  ...  return 123
3  ...
4  >>> callable(func)
5 True
6  >>> func = 123
7  >>> callable(func)
8 False
View Code

chr(i)

返回一个数字在ASCII编码中对应的字符,取值范围256个

    
 1 >>> chr(66)
 2 'B'
 3  >>> chr(5)
 4 'x05'
 5  >>> chr(55)
 6 '7'
 7  >>> chr(255)
 8 'xff'
 9  >>> chr(25)
10 'x19'
11  >>> chr(65)
12 'A'
View Code

classmethod(function)

返回函数的类方法

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

把字符串编译成python可执行的代码

    
 1  >>> str = "for i in range(0,10): print(i)"
 2  >>> c = compile(str,'','exec')
 3  >>> exec(c)
 4 0
 5 1
 6 2
 7 3
 8 4
 9 5
10 6
11 7
12 8
13 9
View Code

complex([real[, imag]])

创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数

    
 1  >>> complex(1, 2)
 2 (1+2j)
 3 # 数字
 4  >>> complex(1)
 5 (1+0j)
 6 # 当做字符串处理
 7  >>> complex("1")
 8 (1+0j)
 9 # 注意:这个地方在“+”号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
10  >>> complex("1+2j")
11 (1+2j)
View Code

delattr(object, name)

删除对象的属性值

    
 1 >>> class cls:
 2 ...   @classmethod
 3 ...   def echo(self):
 4 ...     print('CLS')
 5 ... 
 6 >>> cls.echo()
 7 CLS
 8 >>> delattr(cls, 'echo')
 9 >>> cls.echo()
10 Traceback (most recent call last):
11   File "<stdin>", line 1, in <module>
12 AttributeError: type object 'cls' has no attribute 'echo'
View Code

dict(**kwarg)

创建一个数据类型为字典

1  >>> dic = dict({"k1":"123","k2":"456"})
2  >>> dic
3 {'k1': '123', 'k2': '456'}
View Code

dir([object])

返回一个对象中中的所有方法

1 >>> dir(str)
2 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce\_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
View Code

divmod(a, b)

返回的是a//b(除法取整)以及a对b的余数,返回结果类型为tuple

1  >>> divmod(10, 3)
2 (3, 1)
View Code

enumerate(iterable, start=0)

为元素生成下标

1  >>> li = ["a","b","c"]
2  >>> for n,k in enumerate(li):
3  ...  print(n,k)
4  ...
5 0 a
6 1 b
7 2 c
View Code

eval(expression, globals=None, locals=None)

把一个字符串当作一个表达式去执行

1  >>> string = "1 + 3"
2  >>> string
3 '1 + 3'
4  >>> eval(string)
5 4
View Code

exec(object[, globals[, locals]])

把字符串当作python代码执行

1  >>> exec("for n in range(5): print(n)")
2 0
3 1
4 2
5 3
6 4
View Code

filter(function, iterable)

筛选过滤,循环可迭代的对象,把迭代的对象当作函数的参数,如果符合条件就返回True,否则就返回False

 1  >>> def func(x):
 2  ...  if x == 11 or x == 22:
 3  ...    return True
 4  ...
 5  >>> ret = filter(func,[11,22,33,44])
 6  >>> for n in ret:
 7  ...  print(n)
 8  ...
 9 11
10 22
11 
12 >>> list(filter((lambda x: x > 0),range(-5,5)))
13 [1, 2, 3, 4]
View Code

float([x])

将整数和字符串转换成浮点数

1  >>> float("124")
2 124.0
3  >>> float("123.45")
4 123.45
5  >>> float("-123.34")
6 -123.34
View Code

format(value[, format_spec])

字符串格式化

frozenset([iterable])

frozenset是冻结的集合,它是不可变的,存在哈希值,好处是它可以作为字典的key,也可以作为其它集合的元素。缺点是一旦创建便不能更改,没有add,remove方法。

getattr(object, name[, default])

返回对象的命名属性的值,name必须是字符串,如果字符串是对象属性之一的名称,则结果是该属性的值。

globals()

获取或修改当前文件内的全局变量

1 >>> a = "12"
2 >>> bsd = "54asd"
3 >>> globals()
4 {'__doc__': None, 'a': '12', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'bsd': '54asd', '__builtins__': <module 'builtins' (built-in)>, 'n': '__doc__', '__name__': '__main__', '__spec__': None, '__package__': None}
View Code

hasattr(object, name)

参数是一个对象和一个字符串,如果字符串是对象的某个属性的名称,则结果为True,否则为False。

hash(object)

返回一个对象的hash值

1  >>> a = "asdadasdwqeq234sdfdf"
2  >>> hash(a)
3 5390438057823015497
View Code

help([object])

查看一个类的所有详细方法,或者查看某个方法的使用详细信息

 1  >>> help(list)
 2 Help on class list in module __builtin__:
 3 
 4 class list(object)
 5  |  list() -> new empty list
 6  |  list(iterable) -> new list initialized from iterable's items
 7  |  
 8  |  Methods defined here:
 9  |  
10  |  __add__(...)
11  |      x.__add__(y) <==> x+y
12  |  
13  |  __contains__(...)
14  |      x.__contains__(y) <==> y in x
15  |  
16  |  __delitem__(...)
17  |      x.__delitem__(y) <==> del x[y]
18  |  
19  |  __delslice__(...)
20  |      x.__delslice__(i, j) <==> del x[i:j]
21  |      
22  |      Use of negative indices is not supported.
23 ..........
View Code

hex(x)

获取一个数的十六进制

1  >>> hex(13)
2 '0xd'
View Code

id(object)

返回一个对象的内存地址

1  >>> a = 123
2  >>> id(a)
3 1835400816
View Code

input([prompt])

交互式输入

1  >>> name = input("Pless your name: ")
2 Pless your name: ansheng
3  >>> print(name)
4 ansheng
View Code

int(x, base=10)

获取一个数的十进制

1  >>> int("31")
2 31
View Code

  也可以作为进制转换

1  >>> int(10)
2 10
3  >>> int('0b11',base=2)
4 3
5  >>> int('11',base=8)
6 9
7  >>> int('0xe',base=16)
8 14
View Code

isinstance(object, classinfo)

判断对象是否是这个类创建的

1 >>> li = [11,22,33]
2 >>> isinstance(li,list)
3 True
View Code

issubclass(class, classinfo)

查看一个对象是否为子类

iter(object[, sentinel])

创建一个可迭代的对象

 1  >>> obj = iter([11,22,33,44])
 2  >>> obj
 3 <list_iterator object at 0x000002477DB25198>
 4  >>> for n in obj:
 5  ...  print(n)
 6  ...
 7 11
 8 22
 9 33
10 44
View Code

len(s)

查看一个对象的长度

1  >>> url="ansheng.me"
2  >>> len(url)
3 10
View Code

list([iterable])

创建一个数据类型为列表

1  >>> li = list([11,22,33,44])
2  >>> li
3 [11, 22, 33, 44]
View Code

locals()

返回当前作用域的局部变量,以字典形式输出

1  >>> func()
2  >>> def func():
3  ...  name="ansheng"
4  ...  print(locals())
5  ...
6  >>> func()
7 {'name': 'ansheng'}
View Code

map(function, iterable, …)

对一个序列中的每一个元素都传到函数中执行并返回

1 >>> list(map((lambda x : x +10),[1,2,3,4]))
2 [11, 12, 13, 14]
View Code

max(iterable, *[, key, default])

max(arg1, arg2, *args[, key])

取一个对象中的最大值

1  >>> li = list([11,22,33,44])
2  >>> li = [11,22,33,44]
3  >>> max(li)
4 44
View Code

memoryview(obj)

返回对象obj的内存查看对象

1  >>> import struct
2  >>> buf = struct.pack("i"*12, *list(range(12)))
3  >>> x = memoryview(buf)
4  >>> y = x.cast('i', shape=[2,2,3])
5  >>> print(y.tolist())
6 [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
View Code

min(iterable, *[, key, default])

min(arg1, arg2, *args[, key])

取一个对象中的最小值

1 min(iterable, *[, key, default])
2 
3 min(arg1, arg2, *args[, key])
4 
5     取一个对象中的最小值
View Code

next(iterator[, default])

每次只拿取可迭代对象的一个元素

 1  >>> obj = iter([11,22,33,44])
 2  >>> next(obj)
 3 11
 4  >>> next(obj)
 5 22
 6  >>> next(obj)
 7 33
 8  >>> next(obj)
 9 44
10  >>> next(obj)
11  # 如果没有可迭代的元素了就会报错
12 Traceback (most recent call last):
13   File "<stdin>", line 1, in <module>
14 StopIteration
View Code

object

返回一个新的无特征对象

oct(x)

获取一个字符串的八进制

1  >>> oct(13)
2 '0o15'
View Code

open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

文件操作的函数,用来做文件操作的

1  # 打开一个文件
2 - >>> f = open("a.txt","r")
View Code

ord(c)

把一个字母转换为ASCII对对应表中的数字

1  >>> ord("a")
2 97
3  >>> ord("t")
4 116
View Code

pow(x, y[, z])

返回一个数的N次方

1  >>> pow(2, 10)
2 1024
3  >>> pow(2, 20)
4 1048576
View Code

print(*objects, sep=’ ‘, end=’ ’, file=sys.stdout, flush=False)

打印输出

1 >>> print("hello word")
2 hello word
View Code

property(fget=None, fset=None, fdel=None, doc=None)

range(start, stop[, step])

生成一个序列

 1  >>> range(10)
 2 range(0, 10)
 3  >>> for n in range(5):
 4  ...  print(n)
 5  ...
 6 0
 7 1
 8 2
 9 3
10 4
View Code

repr(object)

返回一个包含对象的可打印表示的字符串

1 >>> repr(111)
2 '111'
3 >>> repr(111.11)
4 '111.11'
View Code

reversed(seq)

对一个对象的元素进行反转

 1  >>> li = [1, 2, 3, 4]
 2  >>> reversed(li)
 3 <list_reverseiterator object at 0x000002CF0EF6A940>
 4  >>> for n in reversed(li):
 5  ...  print(n)
 6  ...
 7 4
 8 3
 9 2
10 1
View Code

round(number[, ndigits])

四舍五入

1  >>> round(3.3)
2 3
3  >>> round(3.7)
4 4
View Code

set([iterable])

创建一个数据类型为集合

1  >>> varss = set([11,222,333])
2  >>> type(varss)
3 <class 'set'>
View Code

setattr(object, name, value)

为某个对象设置一个属性

slice(start, stop[, step])

元素的切片操作都是调用的这个方法

sorted(iterable[, key][, reverse])

为一个对象的元素进行排序

 1 #!/usr/bin/env python
 2 # _*_ coding:utf-8 _*_
 3 
 4 char=['',"123", "1", "25", "65","679999999999", "a","B","alex","c" ,"A", "_", "",'a钱','','',"", '',"", "", "", "钲钲㽙㽙㽙"]
 5 
 6 new_chat = sorted(char)
 7 print(new_chat)
 8 for i in new_chat:
 9     print(bytes(i, encoding='utf-8'))
10 
11 
12 # 输出结果:
13 C:Python35python.exe F:/Python_code/Note/soretd.py
14 ['1', '123', '25', '65', '679999999999', 'A', 'B', '_', 'a', 'alex', 'a钱', 'c', '', '', '', '', '', '', '', '', '钲钲㽙㽙㽙', '']
15 b'1'
16 b'123'
17 b'25'
18 b'65'
19 b'679999999999'
20 b'A'
21 b'B'
22 b'_'
23 b'a'
24 b'alex'
25 b'axe9x92xb1'
26 b'c'
27 b'xe1x92xb2'
28 b'xe3xbdx99'
29 b'xe4xbdx97'
30 b'xe4xbdx98'
31 b'xe4xbdx99'
32 b'xe5xadx99'
33 b'xe6x9dx8e'
34 b'xe8xb5xb5'
35 b'xe9x92xb2xe9x92xb2xe3xbdx99xe3xbdx99xe3xbdx99'
36 b'xe9x93xb1'
37 
38 Process finished with exit code 0
View Code

staticmethod(function)

返回函数的静态方法

str(object=b’’, encoding=’utf-8’, errors=’strict’)

字符串

1  >>> a = str(111)
2  >>> type(a)
3 <class 'str'>
View Code

sum(iterable[, start])

求和

1  >>> sum([11,22,33])
2 66
View Code

super([type[, object-or-type]])

执行父类的构造方法

tuple([iterable])

创建一个对象,数据类型为元组

1 >>> tup = tuple([11,22,33,44])
2 >>> type(tup)
3 <class 'tuple'>
View Code

type(object)

查看一个对象的数据类型

1  >>> a = 1
2  >>> type(a)
3 <class 'int'>
4  >>> a = "str"
5  >>> type(a)
6 <class 'str'>
View Code

vars([object])

   查看一个对象里面有多少个变量

zip(*iterables)

将两个元素相同的序列转换为字典

1 >>> li1 = ["k1","k2","k3"]
2 >>> li2 = ["a","b","c"]
3 >>> d = dict(zip(li1,li2))
4 >>> d
5 {'k1': 'a', 'k2': 'b', 'k3': 'c'}
View Code

__import__(name, globals=None, locals=None, fromlist=(), level=0)

导入模块,把导入的模块作为一个别名

生成随机验证码例子

   生成一个六位的随机验证码,且包含数字,数字的位置随机

 1 # 导入random模块
 2 import random
 3 temp = ""
 4 for i in range(6):
 5     num = random.randrange(0,4)
 6     if num == 3 or num == 1:
 7         rad2 = random.randrange(0,10)
 8         temp = temp + str(rad2)
 9     else:
10         rad1 = random.randrange(65,91)
11         c1 = chr(rad1)
12         temp = temp + c1
13 print(temp)
14 
15 
16 输出结果:
17 C:Python35python.exe F:/Python_code/sublime/Day06/built_in.py
18 72TD11
View Code


exec()将自字符串类型的代码执行exec()将自字符串类型的代码执行

exec()

原文地址:https://www.cnblogs.com/panfb/p/7810379.html