<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當前位置: 首頁 - 科技 - 知識百科 - 正文

        Python全棧之路系列之Python3內置函數

        來源:懂視網 責編:小采 時間:2020-11-27 14:26:51
        文檔

        Python全棧之路系列之Python3內置函數

        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 Functionsabs()dict()help()min()setattr()all()dir()hex()next()slice()any()pmod()id()objec
        推薦度:
        導讀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 Functionsabs()dict()help()min()setattr()all()dir()hex()next()slice()any()pmod()id()objec

        內置函數詳解

        abs(x)

        返回數字的絕對值,參數可以是整數或浮點數,如果參數是復數,則返回其大小。

        # 如果參數是復數,則返回其大小。
         >>> abs(-25)
        25
         >>> abs(25)
        25

        all(iterable)

        all()會循環括號內的每一個元素,如果括號內的所有元素都是真的,或者如果iterable為空,則返回True,如果有一個為假的那么就返回False

        >>> all([])
        True
        >>> all([1,2,3])
        True
        >>> all([1,2,""])
        False
        # 如果有一個為假,則都為假
        >>> all([1,2,None])
        False

        假的參數有:False0None""[](){}等,查看一個元素是否為假可以使用bool進行查看。

        any(iterable)

        循環元素,如果有一個元素為真,那么就返回True,否則就返回False

         >>> any([0,1])
        True
         >>> any([0])
        False

        ascii(object)

        在對象的類中尋找__repr__方法,獲取返回值

         >>> class Foo:
         ... def __repr_(self):
         ... return "hello"
         ...
         >>> obj = Foo()
         >>> r = ascii(obj)
         >>> print(r)
        # 返回的是一個可迭代的對象
        <__main__.Foo object at 0x000001FDEE13D320>

        bin(x)

        將整數x轉換為二進制字符串,如果x不為Python中int類型,x必須包含方法__index__()并且返回值為integer

        # 返回一個整數的二進制
         >>> bin(999)
        '0b1111100111'
        # 非整型的情況,必須包含__index__()方法切返回值為integer的類型
         >>> class myType:
         ... def __index__(self):
         ... return 35
         ...
         >>> myvar = myType()
         >>> bin(myvar)
        '0b100011'

        bool([x])

        查看一個元素的布爾值,非真即假

         >>> bool(0)
        False
         >>> bool(1)
        True
         >>> bool([1])
        True
         >>> bool([10])
        True

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

        返回一個byte數組,Bytearray類型是一個可變的序列,并且序列中的元素的取值范圍為 [0 ,255]。

        source參數:

        1. 如果source為整數,則返回一個長度為source的初始化數組;

        2. 如果source為字符串,則按照指定的encoding將字符串轉換為字節序列;

        3. 如果source為可迭代類型,則元素必須為[0 ,255]中的整數;

        4. 如果source為與buffer接口一致的對象,則此對象也可以被用于初始化bytearray.。

         >>> bytearray(3)
        bytearray(b'x00x00x00')

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

         >>> bytes("asdasd",encoding="utf-8")
        b'asdasd'

        callable(object)

        返回一個對象是否可以被執行

         >>> def func():
         ... return 123
         ...
         >>> callable(func)
        True
         >>> func = 123
         >>> callable(func)
        False

        chr(i)

        返回一個數字在ASCII編碼中對應的字符,取值范圍256個

         >>> chr(66)
        'B'
         >>> chr(5)
        'x05'
         >>> chr(55)
        '7'
         >>> chr(255)
        'xff'
         >>> chr(25)
        'x19'
         >>> chr(65)
        'A'

        classmethod(function)

        返回函數的類方法

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

        把字符串編譯成python可執行的代碼

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

        complex([real[, imag]])

        創建一個值為real + imag * j的復數或者轉化一個字符串或數為復數。如果第一個參數為字符串,則不需要指定第二個參數

         >>> complex(1, 2)
        (1+2j)
        # 數字
         >>> complex(1)
        (1+0j)
        # 當做字符串處理
         >>> complex("1")
        (1+0j)
        # 注意:這個地方在“+”號兩邊不能有空格,也就是不能寫成"1 + 2j",應該是"1+2j",否則會報錯
         >>> complex("1+2j")
        (1+2j)

        delattr(object, name)

        刪除對象的屬性值

        >>> class cls:
        ... @classmethod
        ... def echo(self):
        ... print('CLS')
        ... 
        >>> cls.echo()
        CLS
        >>> delattr(cls, 'echo')
        >>> cls.echo()
        Traceback (most recent call last):
         File "<stdin>", line 1, in <module>
        AttributeError: type object 'cls' has no attribute 'echo'

        dict(**kwarg)

        創建一個數據類型為字典

         >>> dic = dict({"k1":"123","k2":"456"})
         >>> dic
        {'k1': '123', 'k2': '456'}

        dir([object])

        返回一個對象中中的所有方法

         >>> dir(str)
        ['__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']

        pmod(a, b)

        返回的是a//b(除法取整)以及a對b的余數,返回結果類型為tuple

         >>> pmod(10, 3)
        (3, 1)

        enumerate(iterable, start=0)

        為元素生成下標

         >>> li = ["a","b","c"]
         >>> for n,k in enumerate(li):
         ... print(n,k)
         ...
        0 a
        1 b
        2 c

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

        把一個字符串當作一個表達式去執行

         >>> string = "1 + 3"
         >>> string
        '1 + 3'
         >>> eval(string)
        4

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

        把字符串當作python代碼執行

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

        filter(function, iterable)

        篩選過濾,循環可迭代的對象,把迭代的對象當作函數的參數,如果符合條件就返回True,否則就返回False

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

        float([x])

        將整數和字符串轉換成浮點數

         >>> float("124")
        124.0
         >>> float("123.45")
        123.45
         >>> float("-123.34")
        -123.34

        format(value[, format_spec])

        字符串格式化

        詳鍵:http://www.gxlcms.com/

        frozenset([iterable])

        frozenset是凍結的集合,它是不可變的,存在哈希值,好處是它可以作為字典的key,也可以作為其它集合的元素。缺點是一旦創建便不能更改,沒有add,remove方法。

        getattr(object, name[, default])

        返回對象的命名屬性的值,name必須是字符串,如果字符串是對象屬性之一的名稱,則結果是該屬性的值。

        globals()

        獲取或修改當前文件內的全局變量

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

        hasattr(object, name)

        參數是一個對象和一個字符串,如果字符串是對象的某個屬性的名稱,則結果為True,否則為False。

        hash(object)

        返回一個對象的hash值

         >>> a = "asdadasdwqeq234sdfdf"
         >>> hash(a)
        5390438057823015497

        help([object])

        查看一個類的所有詳細方法,或者查看某個方法的使用詳細信息

         >>> help(list)
        Help on class list in module __builtin__:
        
        class list(object)
         | list() -> new empty list
         | list(iterable) -> new list initialized from iterable's items
         | 
         | Methods defined here:
         | 
         | __add__(...)
         | x.__add__(y) <==> x+y
         | 
         | __contains__(...)
         | x.__contains__(y) <==> y in x
         | 
         | __delitem__(...)
         | x.__delitem__(y) <==> del x[y]
         | 
         | __delslice__(...)
         | x.__delslice__(i, j) <==> del x[i:j]
         | 
         | Use of negative indices is not supported.
        ..........

        hex(x)

        獲取一個數的十六進制

         >>> hex(13)
        '0xd'

        id(object)

        返回一個對象的內存地址

         >>> a = 123
         >>> id(a)
        1835400816

        input([prompt])

        交互式輸入

         >>> name = input("Pless your name: ")
        Pless your name: ansheng
         >>> print(name)
        ansheng

        int(x, base=10)

        獲取一個數的十進制

         >>> int("31")
        31

        也可以作為進制轉換

         >>> int(10)
        10
         >>> int('0b11',base=2)
        3
         >>> int('11',base=8)
        9
         >>> int('0xe',base=16)
        14

        isinstance(object, classinfo)

        判斷對象是否是這個類創建的

        >>> li = [11,22,33]
        >>> isinstance(li,list)
        True

        issubclass(class, classinfo)

        查看一個對象是否為子類

        iter(object[, sentinel])

        創建一個可迭代的對象

         >>> obj = iter([11,22,33,44])
         >>> obj
        <list_iterator object at 0x000002477DB25198>
         >>> for n in obj:
         ... print(n)
         ...
        11
        22
        33
        44

        len(s)

        查看一個對象的長度

         >>> url="ansheng.me"
         >>> len(url)
        10

        list([iterable])

        創建一個數據類型為列表

         >>> li = list([11,22,33,44])
         >>> li
        [11, 22, 33, 44]

        locals()

        返回當前作用域的局部變量,以字典形式輸出

         >>> func()
         >>> def func():
         ... name="ansheng"
         ... print(locals())
         ...
         >>> func()
        {'name': 'ansheng'}

        map(function, iterable, ...)

        對一個序列中的每一個元素都傳到函數中執行并返回

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

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

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

        取一個對象中的最大值

         >>> li = list([11,22,33,44])
         >>> li = [11,22,33,44]
         >>> max(li)
        44

        memoryview(obj)

        返回對象obj的內存查看對象

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

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

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

        取一個對象中的最小值

         >>> li = list([11,22,33,44])
         >>> li = [11,22,33,44]
         >>> min(li)
        11

        next(iterator[, default])

        每次只拿取可迭代對象的一個元素

         >>> obj = iter([11,22,33,44])
         >>> next(obj)
        11
         >>> next(obj)
        22
         >>> next(obj)
        33
         >>> next(obj)
        44
         >>> next(obj)
         # 如果沒有可迭代的元素了就會報錯
        Traceback (most recent call last):
         File "<stdin>", line 1, in <module>
        StopIteration

        object

        返回一個新的無特征對象

        oct(x)

        獲取一個字符串的八進制

         >>> oct(13)
        '0o15'

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

        文件操作的函數,用來做文件操作的

         # 打開一個文件
        - >>> f = open("a.txt","r")

        ord(c)

        把一個字母轉換為ASCII對對應表中的數字

         >>> ord("a")
        97
         >>> ord("t")
        116

        pow(x, y[, z])

        返回一個數的N次方

         >>> pow(2, 10)
        1024
         >>> pow(2, 20)
        1048576

        print(*objects, sep=' ', end='n', file=sys.stdout, flush=False)

        打印輸出

         >>> print("hello word")
        hello word

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

        range(start, stop[, step])

        生成一個序列

         >>> range(10)
        range(0, 10)
         >>> for n in range(5):
         ... print(n)
         ...
        0
        1
        2
        3
        4

        repr(object)

        返回一個包含對象的可打印表示的字符串

        >>> repr(111)
        '111'
        >>> repr(111.11)
        '111.11'

        reversed(seq)

        對一個對象的元素進行反轉

         >>> li = [1, 2, 3, 4]
         >>> reversed(li)
        <list_reverseiterator object at 0x000002CF0EF6A940>
         >>> for n in reversed(li):
         ... print(n)
         ...
        4
        3
        2
        1

        round(number[, ndigits])

        四舍五入

         >>> round(3.3)
        3
         >>> round(3.7)
        4

        set([iterable])

        創建一個數據類型為集合

         >>> varss = set([11,222,333])
         >>> type(varss)
        <class 'set'>

        setattr(object, name, value)

        為某個對象設置一個屬性

        slice(start, stop[, step])

        元素的切片操作都是調用的這個方法

        sorted(iterable, key)

        為一個對象的元素進行排序

        代碼:

        #!/usr/bin/env python
        # _*_ coding:utf-8 _*_
        
        char=['趙',"123", "1", "25", "65","679999999999", "a","B","alex","c" ,"A", "_", "?",'a錢','孫','李',"余", '佘',"佗", "?", "銥", "鉦鉦???"]
        
        new_chat = sorted(char)
        print(new_chat)
        for i in new_chat:
         print(bytes(i, encoding='utf-8'))

        輸出結果:

        C:Python35python.exe F:/Python_code/Note/soretd.py
        ['1', '123', '25', '65', '679999999999', 'A', 'B', '_', 'a', 'alex', 'a錢', 'c', '?', '?', '佗', '佘', '余', '孫', '李', '趙', '鉦鉦???', '銥']
        b'1'
        b'123'
        b'25'
        b'65'
        b'679999999999'
        b'A'
        b'B'
        b'_'
        b'a'
        b'alex'
        b'axe9x92xb1'
        b'c'
        b'xe1x92xb2'
        b'xe3xbdx99'
        b'xe4xbdx97'
        b'xe4xbdx98'
        b'xe4xbdx99'
        b'xe5xadx99'
        b'xe6x9dx8e'
        b'xe8xb5xb5'
        b'xe9x92xb2xe9x92xb2xe3xbdx99xe3xbdx99xe3xbdx99'
        b'xe9x93xb1'
        
        Process finished with exit code 0

        staticmethod(function)

        返回函數的靜態方法

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

        字符串

         >>> a = str(111)
         >>> type(a)
        <class 'str'>

        sum(iterable[, start])

        求和

         >>> sum([11,22,33])
        66

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

        執行父類的構造方法

        tuple([iterable])

        創建一個對象,數據類型為元組

        >>> tup = tuple([11,22,33,44])
        >>> type(tup)
        <class 'tuple'>

        type(object)

        查看一個對象的數據類型

         >>> a = 1
         >>> type(a)
        <class 'int'>
         >>> a = "str"
         >>> type(a)
        <class 'str'>

        vars([object])

        查看一個對象里面有多少個變量

        zip(*iterables)

        將兩個元素相同的序列轉換為字典

        >>> li1 = ["k1","k2","k3"]
        >>> li2 = ["a","b","c"]
        >>> d = dict(zip(li1,li2))
        >>> d
        {'k1': 'a', 'k2': 'b', 'k3': 'c'}

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

        導入模塊,把導入的模塊作為一個別名

        生成隨機驗證碼例子

        生成一個六位的隨機驗證碼,且包含數字,數字的位置隨機

        # 導入random模塊
        import random
        temp = ""
        for i in range(6):
         num = random.randrange(0,4)
         if num == 3 or num == 1:
         rad2 = random.randrange(0,10)
         temp = temp + str(rad2)
         else:
         rad1 = random.randrange(65,91)
         c1 = chr(rad1)
         temp = temp + c1
        print(temp)

        輸出結果

        C:Python35python.exe F:/Python_code/sublime/Day06/built_in.py
        72TD11

        原文鏈接

        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()pmod()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()

        官方介紹:http://www.gxlcms.com/

        內置函數詳解

        abs(x)

        返回數字的絕對值,參數可以是整數或浮點數,如果參數是復數,則返回其大小。

        # 如果參數是復數,則返回其大小。
         >>> abs(-25)
        25
         >>> abs(25)
        25

        all(iterable)

        all()會循環括號內的每一個元素,如果括號內的所有元素都是真的,或者如果iterable為空,則返回True,如果有一個為假的那么就返回False

        >>> all([])
        True
        >>> all([1,2,3])
        True
        >>> all([1,2,""])
        False
        # 如果有一個為假,則都為假
        >>> all([1,2,None])
        False

        假的參數有:False0None""[](){}等,查看一個元素是否為假可以使用bool進行查看。

        any(iterable)

        循環元素,如果有一個元素為真,那么就返回True,否則就返回False

         >>> any([0,1])
        True
         >>> any([0])
        False

        ascii(object)

        在對象的類中尋找__repr__方法,獲取返回值

         >>> class Foo:
         ... def __repr_(self):
         ... return "hello"
         ...
         >>> obj = Foo()
         >>> r = ascii(obj)
         >>> print(r)
        # 返回的是一個可迭代的對象
        <__main__.Foo object at 0x000001FDEE13D320>

        bin(x)

        將整數x轉換為二進制字符串,如果x不為Python中int類型,x必須包含方法__index__()并且返回值為integer

        # 返回一個整數的二進制
         >>> bin(999)
        '0b1111100111'
        # 非整型的情況,必須包含__index__()方法切返回值為integer的類型
         >>> class myType:
         ... def __index__(self):
         ... return 35
         ...
         >>> myvar = myType()
         >>> bin(myvar)
        '0b100011'

        bool([x])

        查看一個元素的布爾值,非真即假

         >>> bool(0)
        False
         >>> bool(1)
        True
         >>> bool([1])
        True
         >>> bool([10])
        True

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

        返回一個byte數組,Bytearray類型是一個可變的序列,并且序列中的元素的取值范圍為 [0 ,255]。

        source參數:

        1. 如果source為整數,則返回一個長度為source的初始化數組;

        2. 如果source為字符串,則按照指定的encoding將字符串轉換為字節序列;

        3. 如果source為可迭代類型,則元素必須為[0 ,255]中的整數;

        4. 如果source為與buffer接口一致的對象,則此對象也可以被用于初始化bytearray.。

         >>> bytearray(3)
        bytearray(b'x00x00x00')

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

         >>> bytes("asdasd",encoding="utf-8")
        b'asdasd'

        callable(object)

        返回一個對象是否可以被執行

         >>> def func():
         ... return 123
         ...
         >>> callable(func)
        True
         >>> func = 123
         >>> callable(func)
        False

        chr(i)

        返回一個數字在ASCII編碼中對應的字符,取值范圍256個

         >>> chr(66)
        'B'
         >>> chr(5)
        'x05'
         >>> chr(55)
        '7'
         >>> chr(255)
        'xff'
         >>> chr(25)
        'x19'
         >>> chr(65)
        'A'

        classmethod(function)

        返回函數的類方法

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

        把字符串編譯成python可執行的代碼

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

        complex([real[, imag]])

        創建一個值為real + imag * j的復數或者轉化一個字符串或數為復數。如果第一個參數為字符串,則不需要指定第二個參數

         >>> complex(1, 2)
        (1+2j)
        # 數字
         >>> complex(1)
        (1+0j)
        # 當做字符串處理
         >>> complex("1")
        (1+0j)
        # 注意:這個地方在“+”號兩邊不能有空格,也就是不能寫成"1 + 2j",應該是"1+2j",否則會報錯
         >>> complex("1+2j")
        (1+2j)

        delattr(object, name)

        刪除對象的屬性值

        >>> class cls:
        ... @classmethod
        ... def echo(self):
        ... print('CLS')
        ... 
        >>> cls.echo()
        CLS
        >>> delattr(cls, 'echo')
        >>> cls.echo()
        Traceback (most recent call last):
         File "<stdin>", line 1, in <module>
        AttributeError: type object 'cls' has no attribute 'echo'

        dict(**kwarg)

        創建一個數據類型為字典

         >>> dic = dict({"k1":"123","k2":"456"})
         >>> dic
        {'k1': '123', 'k2': '456'}

        dir([object])

        返回一個對象中中的所有方法

         >>> dir(str)
        ['__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']

        pmod(a, b)

        返回的是a//b(除法取整)以及a對b的余數,返回結果類型為tuple

         >>> pmod(10, 3)
        (3, 1)

        enumerate(iterable, start=0)

        為元素生成下標

         >>> li = ["a","b","c"]
         >>> for n,k in enumerate(li):
         ... print(n,k)
         ...
        0 a
        1 b
        2 c

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

        把一個字符串當作一個表達式去執行

         >>> string = "1 + 3"
         >>> string
        '1 + 3'
         >>> eval(string)
        4

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

        把字符串當作python代碼執行

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

        filter(function, iterable)

        篩選過濾,循環可迭代的對象,把迭代的對象當作函數的參數,如果符合條件就返回True,否則就返回False

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

        float([x])

        將整數和字符串轉換成浮點數

         >>> float("124")
        124.0
         >>> float("123.45")
        123.45
         >>> float("-123.34")
        -123.34

        format(value[, format_spec])

        字符串格式化

        詳鍵:http://www.gxlcms.com/

        frozenset([iterable])

        frozenset是凍結的集合,它是不可變的,存在哈希值,好處是它可以作為字典的key,也可以作為其它集合的元素。缺點是一旦創建便不能更改,沒有add,remove方法。

        getattr(object, name[, default])

        返回對象的命名屬性的值,name必須是字符串,如果字符串是對象屬性之一的名稱,則結果是該屬性的值。

        globals()

        獲取或修改當前文件內的全局變量

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

        hasattr(object, name)

        參數是一個對象和一個字符串,如果字符串是對象的某個屬性的名稱,則結果為True,否則為False。

        hash(object)

        返回一個對象的hash值

         >>> a = "asdadasdwqeq234sdfdf"
         >>> hash(a)
        5390438057823015497

        help([object])

        查看一個類的所有詳細方法,或者查看某個方法的使用詳細信息

         >>> help(list)
        Help on class list in module __builtin__:
        
        class list(object)
         | list() -> new empty list
         | list(iterable) -> new list initialized from iterable's items
         | 
         | Methods defined here:
         | 
         | __add__(...)
         | x.__add__(y) <==> x+y
         | 
         | __contains__(...)
         | x.__contains__(y) <==> y in x
         | 
         | __delitem__(...)
         | x.__delitem__(y) <==> del x[y]
         | 
         | __delslice__(...)
         | x.__delslice__(i, j) <==> del x[i:j]
         | 
         | Use of negative indices is not supported.
        ..........

        hex(x)

        獲取一個數的十六進制

         >>> hex(13)
        '0xd'

        id(object)

        返回一個對象的內存地址

         >>> a = 123
         >>> id(a)
        1835400816

        input([prompt])

        交互式輸入

         >>> name = input("Pless your name: ")
        Pless your name: ansheng
         >>> print(name)
        ansheng

        int(x, base=10)

        獲取一個數的十進制

         >>> int("31")
        31

        也可以作為進制轉換

         >>> int(10)
        10
         >>> int('0b11',base=2)
        3
         >>> int('11',base=8)
        9
         >>> int('0xe',base=16)
        14

        isinstance(object, classinfo)

        判斷對象是否是這個類創建的

        >>> li = [11,22,33]
        >>> isinstance(li,list)
        True

        issubclass(class, classinfo)

        查看一個對象是否為子類

        iter(object[, sentinel])

        創建一個可迭代的對象

         >>> obj = iter([11,22,33,44])
         >>> obj
        <list_iterator object at 0x000002477DB25198>
         >>> for n in obj:
         ... print(n)
         ...
        11
        22
        33
        44

        len(s)

        查看一個對象的長度

         >>> url="ansheng.me"
         >>> len(url)
        10

        list([iterable])

        創建一個數據類型為列表

         >>> li = list([11,22,33,44])
         >>> li
        [11, 22, 33, 44]

        locals()

        返回當前作用域的局部變量,以字典形式輸出

         >>> func()
         >>> def func():
         ... name="ansheng"
         ... print(locals())
         ...
         >>> func()
        {'name': 'ansheng'}

        map(function, iterable, ...)

        對一個序列中的每一個元素都傳到函數中執行并返回

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

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

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

        取一個對象中的最大值

         >>> li = list([11,22,33,44])
         >>> li = [11,22,33,44]
         >>> max(li)
        44

        memoryview(obj)

        返回對象obj的內存查看對象

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

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

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

        取一個對象中的最小值

         >>> li = list([11,22,33,44])
         >>> li = [11,22,33,44]
         >>> min(li)
        11

        next(iterator[, default])

        每次只拿取可迭代對象的一個元素

         >>> obj = iter([11,22,33,44])
         >>> next(obj)
        11
         >>> next(obj)
        22
         >>> next(obj)
        33
         >>> next(obj)
        44
         >>> next(obj)
         # 如果沒有可迭代的元素了就會報錯
        Traceback (most recent call last):
         File "<stdin>", line 1, in <module>
        StopIteration

        object

        返回一個新的無特征對象

        oct(x)

        獲取一個字符串的八進制

         >>> oct(13)
        '0o15'

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

        文件操作的函數,用來做文件操作的

         # 打開一個文件
        - >>> f = open("a.txt","r")

        ord(c)

        把一個字母轉換為ASCII對對應表中的數字

         >>> ord("a")
        97
         >>> ord("t")
        116

        pow(x, y[, z])

        返回一個數的N次方

         >>> pow(2, 10)
        1024
         >>> pow(2, 20)
        1048576

        print(*objects, sep=' ', end='n', file=sys.stdout, flush=False)

        打印輸出

         >>> print("hello word")
        hello word

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

        range(start, stop[, step])

        生成一個序列

         >>> range(10)
        range(0, 10)
         >>> for n in range(5):
         ... print(n)
         ...
        0
        1
        2
        3
        4

        repr(object)

        返回一個包含對象的可打印表示的字符串

        >>> repr(111)
        '111'
        >>> repr(111.11)
        '111.11'

        reversed(seq)

        對一個對象的元素進行反轉

         >>> li = [1, 2, 3, 4]
         >>> reversed(li)
        <list_reverseiterator object at 0x000002CF0EF6A940>
         >>> for n in reversed(li):
         ... print(n)
         ...
        4
        3
        2
        1

        round(number[, ndigits])

        四舍五入

         >>> round(3.3)
        3
         >>> round(3.7)
        4

        set([iterable])

        創建一個數據類型為集合

         >>> varss = set([11,222,333])
         >>> type(varss)
        <class 'set'>

        setattr(object, name, value)

        為某個對象設置一個屬性

        slice(start, stop[, step])

        元素的切片操作都是調用的這個方法

        sorted(iterable, key)

        為一個對象的元素進行排序

        代碼:

        #!/usr/bin/env python
        # _*_ coding:utf-8 _*_
        
        char=['趙',"123", "1", "25", "65","679999999999", "a","B","alex","c" ,"A", "_", "?",'a錢','孫','李',"余", '佘',"佗", "?", "銥", "鉦鉦???"]
        
        new_chat = sorted(char)
        print(new_chat)
        for i in new_chat:
         print(bytes(i, encoding='utf-8'))

        輸出結果:

        C:Python35python.exe F:/Python_code/Note/soretd.py
        ['1', '123', '25', '65', '679999999999', 'A', 'B', '_', 'a', 'alex', 'a錢', 'c', '?', '?', '佗', '佘', '余', '孫', '李', '趙', '鉦鉦???', '銥']
        b'1'
        b'123'
        b'25'
        b'65'
        b'679999999999'
        b'A'
        b'B'
        b'_'
        b'a'
        b'alex'
        b'axe9x92xb1'
        b'c'
        b'xe1x92xb2'
        b'xe3xbdx99'
        b'xe4xbdx97'
        b'xe4xbdx98'
        b'xe4xbdx99'
        b'xe5xadx99'
        b'xe6x9dx8e'
        b'xe8xb5xb5'
        b'xe9x92xb2xe9x92xb2xe3xbdx99xe3xbdx99xe3xbdx99'
        b'xe9x93xb1'
        
        Process finished with exit code 0

        staticmethod(function)

        返回函數的靜態方法

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

        字符串

         >>> a = str(111)
         >>> type(a)
        <class 'str'>

        sum(iterable[, start])

        求和

         >>> sum([11,22,33])
        66

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

        執行父類的構造方法

        tuple([iterable])

        創建一個對象,數據類型為元組

        >>> tup = tuple([11,22,33,44])
        >>> type(tup)
        <class 'tuple'>

        type(object)

        查看一個對象的數據類型

         >>> a = 1
         >>> type(a)
        <class 'int'>
         >>> a = "str"
         >>> type(a)
        <class 'str'>

        vars([object])

        查看一個對象里面有多少個變量

        zip(*iterables)

        將兩個元素相同的序列轉換為字典

        >>> li1 = ["k1","k2","k3"]
        >>> li2 = ["a","b","c"]
        >>> d = dict(zip(li1,li2))
        >>> d
        {'k1': 'a', 'k2': 'b', 'k3': 'c'}

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

        導入模塊,把導入的模塊作為一個別名

        生成隨機驗證碼例子

        生成一個六位的隨機驗證碼,且包含數字,數字的位置隨機

        # 導入random模塊
        import random
        temp = ""
        for i in range(6):
         num = random.randrange(0,4)
         if num == 3 or num == 1:
         rad2 = random.randrange(0,10)
         temp = temp + str(rad2)
         else:
         rad1 = random.randrange(65,91)
         c1 = chr(rad1)
         temp = temp + c1
        print(temp)

        輸出結果

        C:Python35python.exe F:/Python_code/sublime/Day06/built_in.py
        72TD11
        更多Python全棧之路系列之Python3內置函數 相關文章請關注PHP中文網!

        聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        Python全棧之路系列之Python3內置函數

        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 Functionsabs()dict()help()min()setattr()all()dir()hex()next()slice()any()pmod()id()objec
        推薦度:
        標簽: 系列 內置 函數
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 国产偷v国产偷v亚洲高清| 男女交性永久免费视频播放 | 国产免费牲交视频免费播放| 国产在线观看免费观看不卡| 亚洲精品在线免费看| 久久不见久久见免费视频7| 亚洲国产一二三精品无码| 国产福利免费视频 | 四虎成年永久免费网站| 亚洲一卡2卡三卡4卡有限公司| 三级毛片在线免费观看| 国产亚洲福利精品一区| 秋霞人成在线观看免费视频| 亚洲精品无码精品mV在线观看| 两个人的视频www免费| 久久91亚洲人成电影网站| 99精品视频免费| 亚洲AV人人澡人人爽人人夜夜 | 在线观看免费播放av片| 亚洲日韩中文无码久久| 国产真人无码作爱视频免费| 亚洲爱情岛论坛永久| 五月婷婷在线免费观看| 国产色在线|亚洲| 午夜视频在线在免费| 高潮毛片无遮挡高清免费| 亚洲一区精品伊人久久伊人| 丝袜足液精子免费视频| 亚洲高清中文字幕| 亚洲大片在线观看| 18禁黄网站禁片免费观看不卡| 亚洲国产精品免费在线观看| 久久精品免费一区二区喷潮| 无遮挡a级毛片免费看| 久久精品国产亚洲av麻| 免费看男女下面日出水来| 亚洲AV日韩AV无码污污网站| 国产精品亚洲精品日韩已方| 久久精品人成免费| 亚洲一本一道一区二区三区| 亚洲欧洲久久久精品|