程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python3 built in functions

編輯:Python
"""
# Built in functions ---abs(): The absolute value
# a = 10086
a = 'hello'
try:
print(abs(a))
with open('666.p', 'r', encoding='utf-8') as f:
print(f.read())
except TypeError:
print('Error: Wrong data type ')
except IOError:
print(' File opening failure ')
else:
print(666)
finally:
print(222)
"""
"""
# Built in functions ---divmod(): Combine the results of divisor and remainder operations , Returns a tuple containing quotient and remainder (a // b, a % b). Divisor Divisor merchant remainder
print(divmod(45, 4))
print(45 / 4)
print(45 // 4)
print(45 % 4)
"""
"""
# Built in functions ---input(): Accept a standard input data , Return to string type .
x = input(' Please enter a string : ')
print(x)
print(type(x))
"""
"""
# Built in functions ---open(): Function to open a file , Create a file object , Related methods can be called to read and write .
# f = open('../run.py', 'r', encoding='utf-8')
# s = f.read()
# f.close()
# print(s)
# with open('../run.py', 'r', encoding='utf-8') as f:
# s = f.read()
# print(s)
"""
"""
# Built in functions ---staticmethod(): The static return method of the function .
class testStaticMethod(object):
@staticmethod
def play():
print(' Static methods ')
def song(self):
print(' Common method ')
# classmethod The function corresponding to the modifier does not need to be instantiated , Unwanted self Parameters , But the first parameter needs to represent the class itself cls Parameters , You can call the properties of a class , Class method , Instanced objects, etc .
@classmethod
def runs(cls):
print(' Class method ')
print(cls)
# Class
# testStaticMethod().play()
# testStaticMethod().song()
# testStaticMethod().runs()
# Class
testStaticMethod.runs()
testStaticMethod.play()
# testStaticMethod.song() # Report errors , Normal methods cannot be called statically , Will report a mistake
"""
'''
# Built in functions ---all(): It is used to judge the given iterative parameters iterable Whether all elements in are TRUE, If it's a return True, Otherwise return to False.
print(all([1, 2, 3]))
print(all([0, 1, 2, 3]))
'''
'''
# Built in functions ---enumerate(): For traversing a data object ( As listing 、 Tuples or strings ) Combined into an index sequence , List both data and data index , Generally used in for Cycle of
lst = [' millet ', ' Huawei ', 'oppo', 'vivo', ' Apple ']
# Mode one :
# for i in lst:
# print(i)
# Mode two :
# for i in range(len(lst)):
# print(i, lst[i])
# Mode three :
# enumerate(): enumeration
# for i in enumerate(lst):
# print(i)
# Mode 4 :
start = 100
for k, v in enumerate(lst, start): # start Omission , The default is 0, k,v--- Unpack
print(k, '====', v)
'''
'''
# Built in functions ---int():
x = '78'
# print(x)
# print(type(x))
print(int(x))
print(type(int(x)))
'''
"""
# Built in functions ---ord():ord() The function is chr() function ( about 8 Bit ASCII character string ) or unichr() function ( about Unicode object ) The pairing function of , It takes one character ( The length is 1 String ) As a parameter , Return the corresponding ASCII The number , perhaps Unicode The number , If given Unicode The characters are beyond your Python Define scope , It will trigger a TypeError It's abnormal .
print(ord('a')) # 97
print(ord('A')) # 65
print(chr(97)) # a
print(chr(65)) # A
"""
"""
# Built in functions ---str(): Convert other objects to strings .
lst = ['apple', 'huawei']
print(str(lst))
print(type(str(lst)))
"""
'''
# Built in functions ---any(): It is used to judge the given iterative parameters iterable Is it all False, Then return to False, If I have a theta True, Then return to True.
lst = ['', None, "", False]
lst1 = ['', None, "", False, 1]
print(any(lst))
print(any(lst1))
'''
"""
# Built in functions ----eval(): Used to execute a string expression , And return the value of the expression . Used to execute a paragraph python Code
eval('print(666)')
"""
"""
# Built in functions ----isinstance(): Determine whether an object is a known type , similar type().
s = 'abc'
print(isinstance(s, str))
number = 5
print(isinstance(number, int))
print(isinstance(s, (str, int, tuple, list, dict, set)))
"""
"""
# Built in functions ---pow(x,y): return x Of y Power Value .
print(pow(2, 3))
print(pow(2, 5))
# Equivalent to : print(2 ** 3)
"""
'''
# Built in functions ---sum(): Sum the series .
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
lst3 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(sum(lst))
print(sum(lst2))
print(sum(lst3))
'''
# Built in functions ---ascii(): Function similar to repr() function , Returns a string representing an object , But for the non in the string ASCII The character returns pass repr() Function USES \x, \u or \U Encoded character . Generating a string is similar to Python2 In the version repr() The return value of the function .
"""
# Built in functions ---bin() Returns an integer int Or long integers long int The binary representation of .
print(bin(10))
print(bin(8))
"""
'''
# bool() Function to convert a given argument to a boolean type , If there are no parameters , return False.
print(bool())
print(bool(0))
print(bool(1))
print(bool('abc'))
print(bool(False))
print(bool(True))
'''
'''
# Built in functions ---bytearray(): Returns a new byte array . The elements in this array are mutable , And the range of values for each element : 0 <= x < 256.
# print(bytearray())
# print(bytearray([1, 2, 3]))
print(bytes([1, 2, 3, 4]))
print(bytes('abc'))
'''
'''
# Built in functions ---chr(): Use an integer as a parameter , Returns a corresponding character .
print(chr(97)) # a
'''
"""
# Built in functions ---compile():
# s = "for i in range(0, 10): print(i)"
# c = compile(s, '', 'exec') # Compile as a bytecode object
'''
lst = ['apple', 'huawei', 'xiaomi']
for i in lst:
print(i)
'''
exec('''
for i in range(6):
print(i)
''')
exec('''
lst = ['apple', 'huawei', 'xiaomi']
for i in lst:
print(i)
''')
"""
'''
# Built in functions ---filter(): For filtering sequence , Filter out the elements that do not meet the conditions , Returns an iterator object , If you want to convert to a list , have access to list() To convert . This accepts two parameters , The first one is a function , The second is the sequence , Each element of the sequence is passed as a parameter to the function for judgment , Then return True or False, And then it will return True Is placed in the new list .
lst = set()
for i in range(101):
lst.add(i)
def is_even(n):
return n % 2 == 0
s = list(filter(is_even, lst))
print(s)
'''
"""
# Built in functions ---float() : Used to convert integers and strings to floating-point numbers .
print(float(12))
print(float(12.05))
print(float(-12.05))
print(float('10086'))
"""
"""
# Built in functions ---format(): adopt {} and : To replace the old % .
print('{} the people {}'.format(' The Chinese ', ' republic '))
print('{name} the people {country}'.format(name=' The Chinese ', country=' republic '))
print('{0}{1}{2}{3}{4}{5}'.format(' The Chinese ', ' the people ', ' republic ', ' The central ', ' the people ', ' The government '))
"""
'''
# Built in functions ---frozenset() Returns a frozen collection , After freezing, no more elements can be added or removed from the collection .
lst = ['one', 'two', 'three']
f = frozenset(lst)
print(lst)
'''
"""
# Built in functions ---getattr(): Used to return an object property value .
class Test():
name = 'shunyuan'
def play(self):
pass
print(getattr(Test(), 'name'))
"""
"""
# Built in functions ---globals(): Returns all global variables of the current location in dictionary type .
print(globals()) # Return global variables
print(''.center(80, '*'))
print(locals()) # Returns the current variable ( If the current location is a global location , Is equivalent to globals(), If used in a function , Return the variables inside the corresponding function )
"""
"""
# Built in functions ---hasattr() : It is used to determine whether the object contains the corresponding properties .
class Test():
x = 'apple'
y = 'xiaomi'
def play(self):
pass
print(hasattr(Test(), 'x'))
print(hasattr(Test(), 'y'))
print(hasattr(Test(), 'z'))
"""
'''
# Built in functions ---hash(): Get an object ( String or number, etc ) Hash value of .
print(hash('abc'))
print(hash('testadmin'))
name1=' Normal program code '
name2=' Normal program code contains virus '
print(hash(name1)) # 2403189487915500087
print(hash(name2)) # -8751655075885266653
'''
"""
# Built in functions ---help(): A detailed description of the purpose of a function or module .
print(help('sys'))
print(help('os'))
print(help([1, 2, 3]))
"""
"""
# Built in functions ---hex(): Converts a specified number to 16 Hexadecimal number .
print(hex(898))
"""
"""
# Built in objects ---id(): To get the memory address of the object .
print(id('abc'))
print(id(123))
"""
"""
# Built in objects ---len(): Returns the object ( character 、 list 、 Tuples etc. ) Length or number of items .
print(len('helloworld'))
print(len([1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(len((1, 2, 3, 4, 5, 6, 7, 8, 9)))
print(len({'a', 'b', 'c', 'd'}))
print(len({'a': 'apple', 'b': 'huawei', 'c': 'xiaomi', 'd': 'oppo'}))
"""
'''
# Built in objects ---list(): Convert tuples or strings to lists .
print(list('abcdefg'))
print(list(('apple', 'huawei', 'xiaomi', 'oppo')))
print(list({'apple', 'huawei', 'xiaomi', 'oppo'}))
print(list({'apple1': 'ok', 'huawei1': 'error', 'xiaomi1': True, 'oppo1': False}))
'''
"""
# Built in functions ---map(): map() Function will map the specified sequence according to the function provided . The first parameter function Call... With each element in the parameter sequence function function , Return contain every time function The function returns a new list of values .
def square(x):
return x ** 2
res = map(square, [1, 2, 3, 4, 5, 6, 7, 8, 9])
for i in res:
print(i, end=',')
"""
'''
# Iteratable object
# lst = [' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ']
# it = lst.__iter__() # Return iterator
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
'''
"""
# Built in functions ---max(): Returns the maximum value of the given parameter , Parameters can be sequences .
print(max((1, 5, 85, 3, 15, 95, 20)))
print(max([1, 5, 85, 3, 15, 95, 20]))
print(max({1, 5, 85, 3, 15, 95, 20}))
# Same as min()
"""
# Built in functions ---memoryview() Function returns the memory view object with the given parameter (Momory view). So called memory view object , Wrap the data that supports the buffer protocol , Allows without the need to copy objects Python Code access .
'''
# Built in functions ---iter(): Used to generate iterators .
lst = ['a', 'b', 'c', 'd']
print(iter(lst)) # <list_iterator object at 0x0000014F7F2B24E0>
'''
"""
# Built in functions ---next(): Returns the next entry for the iterator .
# ' Iteratable object ' and ' iterator ' It's not a concept
lst = ['huawei', 'xiaomi', 'apple', 'oppo'] # Iteratable object
it = lst.__iter__() # iterator
print(next(it))
print(next(it))
print(next(it))
lst2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
it2 = iter(lst2)
print(next(it2))
print(next(it2))
print(next(it2))
print(next(it2))
"""
'''
# Built in functions ---oct(): Converts an integer to 8 Base string .
print(oct(8))
'''
"""
# Built in functions ---range(): Function returns an iteratable object ( Type is object ), Not the list type , So when you print, you don't print the list .Python3 list() Functions are object iterators , You can put range() Turn the returned iteratable object into a list , The returned variable type is list .
for i in range(3):
print(i, ''.center(20, '*'))
for i in list(range(3)):
print(i, ''.center(20, '+'))
print(list(range(3)))
"""
'''
# Built in functions ---reversed(): Returns an inverted iterator .
# lst = 'hello world'
# lst = ('apple', 'huawei', 'xiaomi', 'oppo')
lst = ['apple', 'huawei', 'xiaomi', 'oppo']
print(list(reversed(lst)))
'''
"""
# Built in functions ---round(): Return floating point number x Round the value of .
print(round(70.46895))
print(round(70.56895))
print(round(70.54895, 1))
print(round(70.55895, 1))
print(round(70.55495, 2))
print(round(70.55595, 2))
"""
"""
# Built in functions ---set(): Creates an unordered set of non-repeating elements , Relationship testing is possible , Delete duplicate data , You can also compute the intersection 、 Difference set 、 And set etc. .
# print(set(123456)) # Report errors
print(set('abcdefabcdef'))
print(set(('apple', 'huawei', 'xiaomi')))
print(set(['apple', 'huawei', 'xiaomi']))
print(set({'apple', 'huawei', 'xiaomi'}))
print(set({'first': 'apple', 'second': 'huawei', 'third': 'xiaomi'}))
"""
'''
# Built in functions ---setattr(): The corresponding function is getattr(), Used to set property values , The attribute does not necessarily exist .
class Test():
def play(self):
pass
t = Test() # Class
setattr(t, 'name', ' Newton ')
print(getattr(t, 'name'))
print(t.name)
'''
"""
# Built in functions ---slice(): Implement slice object , It is mainly used for parameter passing in slice operation function .slice(stop) perhaps slice(start, stop[, step])
print(slice(5)) # slice(None, 5, None)
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(lst[:])
print(lst[2:])
print(lst[:5])
print(lst[0:5])
print(lst[2:5])
print(lst[::2])
print(lst[1:6:2])
print(lst[slice(2)]) # If you pass a parameter, it is the end position of the identification
print(lst[slice(6)]) # If you pass a parameter, it is the end position of the identification
print(lst[slice(2, 6)]) # Pass two parameters to identify : Starting position , End position
print(lst[slice(2, 8, 1)]) # Pass two parameters to identify : Starting position , End position
print(lst[slice(2, 8, 2)]) # Pass three parameters to identify : Starting position , End position , step
print(lst[slice(1, 9)]) # Pass two parameters to identify : Starting position , End position
print(''.center(20, '*'))
print(lst[slice(-1, -8, -2)]) # Pass two parameters to identify : Starting position , End position
"""
'''
# Built in functions ---sorted(): Sort all iteratable objects .sort And sorted difference :sort Is used in the list The method on the ,sorted You can sort all iterable objects .list Of sort Method returns an operation on an existing list , And built-in functions sorted Method returns a new one list, Instead of operating on the basis of the original .
# lst = [1, 5, 3, 10, 4, 86, 45, 1, 30, 5, 62, 95, 5]
# lst.sort()
# print(lst)
lst = {1, 5, 3, 10, 4, 86, 45, 1, 30, 5, 62, 95, 5}
print(sorted(lst))
s = 'hello world! abc ABC'
print(sorted(s))
t = (1, 5, 3, 10, 4, 86, 45, 1, 30, 5, 62, 95, 5)
print(sorted(t))
lst2 = [1, 5, 3, 10, 4, 86, 45, 1, 30, 5, 62, 95, 5]
print(sorted(lst2))
dic = {103: "xiaomi", 101: 'huawei', 102: 'apple', 104: 'vivo'}
print(sorted(dic))
'''
"""
# Built in functions ---str() Convert to string object .
s = 'abc'
print(s)
print(str(s))
print(type(str(s)))
lst = ['a', 'b', 'c', 'd']
print(lst)
print(str(lst))
print(type(str(lst)))
t = ('a', 'b', 'c', 'd')
print(t)
print(str(t))
print(type(str(t)))
"""
'''
# Built in functions ---sum(): Sum the series .
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(sum(lst))
t = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(sum(t))
se = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print(sum(se))
dic = {12: 'apple', 56: 'huawei'}
print(sum(dic))
'''
"""
# Built in functions - --tuple(): Convert list to tuple .
print(tuple('abcd'))
print(tuple(['a', 'b', 'c', 'd']))
print(tuple(('a', 'b', 'c', 'd')))
print(tuple({'a', 'b', 'c', 'd'}))
print(tuple({'a': 'ok', 'b': 'error', 'c': True, 'd': False}))
"""
'''
# Built in functions ---type(): If you only have the first parameter, return the type of the object , Three parameters return the new type object .isinstance() And type() difference :type() A subclass is not considered a superclass type , Do not consider inheritance relationships .isinstance() Think of a subclass as a superclass type , Consider inheritance relationships . It is recommended if you want to determine whether two types are the same isinstance().
print(type(1))
print(type(1) == int)
'''
"""
# Built in functions ---vars() : Returns the object object Dictionary object for properties and property values .
class Test():
def __init__(self):
self.name = ' Newton '
self.age = 400
self.sex = ' male '
def play(self):
print(vars(self))
# print(vars(Test))
Test().play()
"""
'''
# zip() Function to take iteratable objects as parameters , Package the corresponding elements in the object into tuples , And then return the objects made up of these tuples , The advantage is that it saves a lot of memory . We can use list() Convert to output list . If the number of elements in each iterator is inconsistent , Returns a list of the same length as the shortest object , utilize * The operator , Tuples can be unzipped into lists .
print(list(zip([100, 200, 300])))
s1 = 'abc'
s2 = 'wxyz'
print(zip(s1, s2))
print(list(zip(s1, s2)))
print(list(zip(s2, s1)))
lst1 = ['first', 'second', 'third']
lst2 = ['xiaomi', 'huawei', 'apple']
print(zip(lst1, lst2))
print(list(zip(lst1, lst2)))
t1 = ('first', 'second', 'third')
t2 = ('xiaomi', 'huawei', 'apple')
print(zip(t1, t2))
print(list(zip(t1, t2)))
se1 = {'first', 'second', 'third'}
se2 = {'xiaomi', 'huawei', 'apple'}
print(list(zip(se1, se2)))
dic1 = {'first': 100, 'second': 200, 'third': 300}
dic2 = {'huawei': 111, 'xiaomi': 222, 'apple': 333}
print(list(zip(dic1, dic2)))
'''
"""
# Transfer of formal parameters : *args--- Accept location parameters , **kwargs--- Accept keyword parameters ; among , Position parameter in front , Keyword parameter after . *args and **kwargs It means parameter aggregation
def func(*args, **kwargs):
print(args) # A tuple type
print(kwargs) # Dictionary type
# func('apple', 'huawei', 'xiaomi', name=' Newton ', age=400, sex=' male ')
# Transfer of arguments : If the actual parameter is preceded by a '*' Number , Indicates the scatter position parameter ; If you add two '**' number , Indicates that the keyword parameters are scattered ; among : When dispersing position parameters , except int Out of type , Other types are OK ; When dispersing keyword parameters , Can only be dictionary type
func(*'apple', *{'first', 'second', 'third'}, *['sex', 'age', 'name'], *('good', 'bad', 'error', 'success'),
*{'one': True, 'two': False}, **{'car': ' Mercedes ', 'price': '100 ten thousand '})
"""
'''
# Packaging compression
a = [1, 2, 3]
b = [' Apple ', ' Huawei ', ' millet ']
c = ['one', 'two', 'third']
d = ['sex', 'name', 'age']
print(list(zip(a, b, c, d))) # A list of tuples
m, n, p = zip(a, b, c, d)
print(m)
print(n)
print(p)
# deconstruction ( Unpack )
x, y = zip(*[(1, ' Apple '), (2, ' Huawei '), (3, ' millet ')])
print(x)
print(y)
'''

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved