Built-in functions of Python basics

Source: Internet
Author: User
Tags abs decimal to binary iterable true true

One, built-in function table (Python 3.x)

1, Mathematical Operation class:

2, the Collection class operation:

3. Logical judgment:

4. Reflection:

5. IO Operation:

Second, the built-in function uses the example:

1, ABS () take absolute value

Print (ABS (3)) print (ABS ( -3)) #取-Absolute value of 3--------output--------    3    3

2, all () when the contents in parentheses are true, the result is true, and vice versa is False

Print (All ("")) #可迭代对象是空的, also returns Trueprint (All ("A", "B")) and print (All ("A", "B", "")) Print (All ("A", "B", "", None)) #只要有一个为False, false---------------------------output--------------------------    true    true    True    False

3, any () in parentheses as long as one is true, the result is true, and vice versa is False

Print (Any ("", none))) Print (Any ((1, "", none)) #只要有一个为True时 with a result of true----------output-----------    False    True

4. Bin () Convert decimal to Binary

Print (Bin (5)) #将5转成二进制-------output-------    0b101 #二进制表达式

5, bool Boolean value NULL, none,0 Boolean value is False, the rest is true

Print (BOOL (")))  #空print (bool (0))  #0print (bool (None))  #Noneprint (bool (" 0 "))  # At this point 0 bits a string----------------output------------------    false false    True

6. Bytes () turn the string into bytes

Content = "Hello" print (bytes (content,encoding= "UTF8")) #手动把字符串编码, go to binary bytes type print (bytes (content,encoding= "UTF8"). Decode ("UTF8")) #需要把字符串进行编码, then decode (with what encoding, what decoding)------------------------output--------------------------    B ' \xe4\ XBD\XA0\XE5\XA5\XBD '    Hello

7, Chr () value corresponding to the ASSCII character

Print (CHR) print (CHR) print (CHR)-----Output-----    A    B    C

8, dir display function built-in properties and methods

Print (dir (dict))----------------output--------------------[' __class__ ', ' __contains__ ', ' __delattr__ ', ' __delitem__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __gt__ ', ' __hash__ ', ' __ Init__ ', ' __init_subclass__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ Ex__ ', ' __repr__ ', ' __setattr__ ', ' __setitem__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' clear ', ' copy ', ' Fromkeys ', ' get ', ' items ', ' Keys ', ' Pop ', ' Popitem ', ' setdefault ', ' Update ', ' values '

9, Divmod to take the remainder of the business, for paging display function

Print (Divmod (10,3))  #得3, 1, 4 pages----------output results---------    (3, 1)

10. Eval to extract the data structure from the string to interpret the string expression

dic={' name ': ' Michael '} #定义一个字典dic_str =str (DIC) #字典类型转成字符串print (DIC_STR) #打印内容print (Type (DIC_STR)) #打印数据类型d1 =eval ( DIC_STR) #eval: The data structure in the string is extracted out of print (D1) #打印内容print (Type (D1)) #打印数据类型---------------output------------------    {' Name ': ' Michael '}    <class ' str ' >    {' name ': ' Michael '}    <class ' Dict ' >

11. Globals Global Variables

PS1:

Name = "Thousand Rivers have water thousand Rivers Moon, cloudless days." "Print (Globals ())---------------------output-------------------------{' __name__ ': ' __main__ ', ' __doc__ ': None, ' __ package__ ': None, ' __loader__ ': <_frozen_importlib_external. Sourcefileloader object at 0x00000000021c9668>, ' __spec__ ': None, ' __annotations__ ': {}, ' __builtins__ ': <module ' Builtins ' (built-in), ' __file__ ': ' f:/michael/day25/built-in function instance. py ', ' __cached__ ': None, ' name ': ' Thousand rivers have water thousand Rivers Moon, Cloudless day. ‘}

PS2:

Name = "Thousand Rivers have water thousand Rivers Moon, cloudless days." The print (__file__) #打印文件路径和文件名------------output---------------f:/michael/day25/built-in function instances. py

PS3:

Globals print global variables, locals print local variables

Name = "Thousand Rivers have water thousand Rivers Moon, cloudless days." "Def Test ():    name1 =" Qian Shan with January, million households all spring.    Print (Globals ())    print (locals ()) test ()---------------------output-------------------------{' __name__ ': ' __main__ ', ' __doc__ ': None, ' __package__ ': None, ' __loader__ ': <_frozen_importlib_external. Sourcefileloaderobject at 0x0000000002209668>, ' __spec__ ': None, ' __annotations__ ': {}, ' __builtins__ ': <module ' Builtins ' (built-in), ' __file__ ': ' f:/michael/day25/built-in function instance. py ', ' __cached__ ': None, ' name ': ' Thousand rivers have water thousand Rivers Moon, Cloudless day. ', ' Test ': <function test at 0x00000000003f3e18>}-----------------Separator line---------------------{' name1 ': ' Qianshan with January, Thousands of households are all spring. ‘}

12, hash () hash data type is immutable data type, non-hash data type can be changed data type

The role of hash: download software on the Internet, to determine whether it was modified by the value of the hash, you know. And when it comes to transmitting data, the hash

Before and after the value is transmitted, it is possible to determine whether the data is complete.

Print (Hash ("DKDGDKHGLKF")) Print (hash ("DKDGDKHGLKFJWIOFWNDNVJSKDFJKLJJ")) name = "Egon" Print (hash (name)) Print ("--- -->before ", hash (name)) name =" Somebody "Print (" =====>after ", hash (name))----------------- Output--------------------83520990650233403217790489956030600654-1821075661332880192----->before- 1821075661332880192=====>after-3592763496452633376

13. Help () View the details of function usage

Print (All)------------output--------------Help on built-in function all in module Builtins:all (iterable,/)    Return true if bool (x) is true to all values x in the iterable.        If the iterable is empty, return True.none

14, Bin, Hex, Oct conversion

Print (BIN) #binary decimal----> Binary print (OCT) #octonary decimal----> octal print (hex) #hexadecimal decimal----> Hex------------------------Output----------------------------    0b1100    0o14    0xc

15. Isinstance Judgment Type

Print (Isinstance (1,int))       #判断是不是int类型print (isinstance (' abc ', str))   #判断字符串print (Isinstance ([],list)     ) #判断列表print (Isinstance ({},dict))     #判断字典print (isinstance ({1,2},set))   # Evaluates the set--------------------output-----------------------True True True True    

16, Max () max () min (min) value

Simple usage:

L = [2,4,0,-2,23]print (max (L)) print (min (l))-----Output-----    2

Advanced usage:

Description

1. The Max function handles an iterative object, which is equivalent to a for loop that extracts each element for comparison;

      Note: Comparisons cannot be made between different types.

2, the comparison between each element, is from the first position of each element is compared, if the location of the size, the back does not need to compare

, the size of the two elements is directly derived.

From the dictionary salary_dic take out the highest-paid person and the lowest person:

Salary_dic = {' Egon ': 290, ' Alex ': 100000000, ' Wupeiqi ': 10000, ' Yuanhao ': 2000}

Print (max (Salary_dic,key=lambda k:salary_dic[k)) #使用匿名函数print (min (Salary_dic,key=lambda k:salary_dic[k]) # Using anonymous functions-------------output-----------------    Alex  #最高的人    Egon  #最低的人

17, Zip () pairs of objects, equivalent to the function of the zipper

Salary_dic = {' Egon ': 290, ' Alex ': 100000000, ' Wupeiqi ': 10000, ' Yuanhao ': 2000}

Print (list (Zip (Salary_dic.keys (), Salary_dic.values ())) Print (list (Zip (["A", "B", "C"],[1,2,3,4,5]))------------ ----Output-------------------[(' Egon ', 290), (' Alex ', 100000000), (' Wupeiqi ', 10000), (' Yuanhao ', ' a ') [(' A ', 1), (' B ', 2 ), (' C ', 3)]

18, reversed () reversal

L = [1,2,4,3]print (list (Reversed (l))) print (l)-------output--------[3, 4, 2, 1] # NOTE: It is reversed in the order of the original list, not sorted by element size [1, 2, 4, 3]

19, round () rounding

Print (Round (3.4)) print (round (3.5))-------output--------    3    4

20, slice () slice

A = "Hello world" a1 = Slice (1,9) #切片a2 = Slice (1,9,2) #加上步长切片print (a[a1])  #1print (A[1:9])   #2  1 and 2 effects are the same as print (A[A2])  #3print (A[1:9:2])  #4  3 and 4 effects are the same as print (A2.start) #开始的索引值print (a2.stop)  #结束的索引值print (a2.step)  # Step----------output-------------    ello wor    ello wor    el o    el o    1    9    2

21, sorted () sort

Or the same as the 16 comparison of wages sort it!

Salary_dic = {' Egon ': 290, ' Alex ': 100000000, ' Wupeiqi ': 10000, ' Yuanhao ': 2000}print (Sorted (salary_dic,key=lambda K: Salary_dic[k]) #工资从低到高print (sorted (salary_dic,key= lambda x:salary_dic[x],reverse=true)) #把反转的巩固一下, Is the salary from high to low sort-----------------output Results------------------[' Egon ', ' Yuanhao ', ' Wupeiqi ', ' Alex ' [' Alex ', ' Wupeiqi ', ' Yuanhao ' , ' Egon ']

22. Import Module

Import Timetime.sleep (3) print (time)---------output--------<module ' time ' (built-in) > #会睡眠3s输出结果

23, __import__ () import a String type module

s = "Time" M = __import__ (s) m.sleep (2) print (m)-----output------<module ' time ' (built-in) > #会睡眠2s输出结果

  

 

Built-in functions of Python basics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.