Python built-in functions

Source: Internet
Author: User

Python built-in functions

There are many built-in functions in Python, which can be used directly without calling modules and are encapsulated by common functions. Let's take a look at the built-in functions in Python.

1. abs ()

Abs () is an absolute value function that converts a negative number to a positive number. It is a common function in a number. The example is as follows:

>>> A =-1.564
>>> B =-8
>>> Abs ()
1.564
>>> Abs (B)
8
2. all ()

All () indicates the input parameter list. If the object of the tuples is True, True is returned. Otherwise, False is returned. Similar to the and () function in Excel, if all values are true, the result is true. This function is mainly used to determine whether all conditions are true. There should be a corresponding function or (). If one is true, it is a real function.

>>> All ([11, 22, 33])
True
>>> All (11,22, 33 ))
True
>>> All ([11, 0, 22])
False
>>> All ([11, "al2x", "sb"])
True

Common False formats: Non3, "", "", [], (), {}, and 0 indicate False. The bool () function returns False.
3. any ()

Any () indicates that if one function is true, it is similar to the or () function in Excel. If one function is true, it is true.

>>> Any ([11, 0, 22])
True
>>> Any ([""])
False
>>> Any (["", ""])
True
>>> Any ((""))
False
>>> Any (, 0 ))
True
4. ascii ()

Ascii () is similar to the _ repr _ () method in the class. Ascii (8) = int. _ repr __().

>>> Class Foo:
... Def _ repr _ (self ):
... Return "bbb"
...
>>> F = Foo ()
>>> Ret = ascii (f)
>>> Ret
'Bbb'
Here is an example:

>>> A = "alex"
>>> Ascii ()
"'Alex '"
>>> A. _ repr __()
"'Alex '"

5. bin ()

Bin () is binary. It converts an integer to binary. bin is the abbreviation of binary. It converts an integer to a binary representation.

>>> Bin (10)
'0b1010'
>>> Bin (-10)
'-0b1010'
>>> Bin( 2.9)
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

6. bool ()

The bool () function determines whether it is true or false.

7. bytearray ()

Bytearray () byte array function. We know that strings are stored in Python as their own. Bytearray () is to convert a string to a byte number.

>>> Bytearray ("Wu page", encoding = "UTF-8 ")
Bytearray (B '\ xe5 \ x90 \ xb4 \ xe4 \ xbd \ xa9 \ xe5 \ xa5 \ x87 ')
As we know, Chinese characters are composed of three bytes, So nine unreadable Byte encoding arrays are output above. Another byes is the output byte in the form of a string bytes ().

8. bytes ()

The bytes () function is similar to the bytearray () function, and is the byte encoding of the output string. Only bytes is output as a string, while bytearray () is output as a byte array.

>>> Bytes ("Wu page", encoding = "UTF-8 ")
B '\ xe5 \ x90 \ xb4 \ xe4 \ xbd \ xa9 \ xe5 \ xa5 \ x87'
We can see that the above is the UTF-8 encoding output in the form of a byte string.

9. callable ()

Callable () is used to determine whether it is executable.

>>> F = lambda x: x + 1
>>> F (5)
6
>>> Callable (f)
True
>>> L ()
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
TypeError: 'LIST' object is not callable
>>> Callable (l ())
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
TypeError: 'LIST' object is not callable
>>> Callable (l)
False
Callable () is used to determine whether a function can be executed. Whether it can be executed after a bracket is added.

10. chr ()

Chr () converts a number into a corresponding encoding. It is often used with ord. the ord () function is used to convert an ascii code to a number. in fact, the chr () function is similar to the char () function in Excle, And the ord () function is similar to the code () function in Excel. It is a function that converts encoding.

>>> Chr (99)
'C'
>>> Chr (65)
'A'
We often use random verification codes to convert random numbers into character formats. For example, we often use random numbers when entering website verification codes or collecting verification codes. Combined with random number. Randow. randint.

11. ord ()

Converts a string to a number to encode the content. View the encoding sequence.

>>> Ord ("")
97
>>> Ord ("-")
45
12. clsaamethod ()
Classmethod () is a method in the class, which is used when it is object-oriented.

13. compile ()

Compile () is used during compilation. Python has an external framework that compiles strings into Python code.

14. complex ()

Complex () is a plural representation. Example:

>>> A = 8
>>> Complex ()
(8 + 0j)

15. delatter ()

Delatter () is used for reflection. Reflection.

16. dict ()

Dict () dictionary, used to define a dictionary.

17. dir ()

You can use dir () to view the methods of class tables.

18. divmod ()

Divmod () division and use, the remainder of the division of two numbers. Divmod () returns a tuples. The front part is the integer part of the integral part, followed by the remainder part. The example is as follows:
>>> Ret = divmod (5, 3)
>>> Ret
(1, 2)
>>> Res = divmod (10, 5)
>>> Res
(2, 0)

>>> Type (ret)
<Class 'tuple'>

From the code above, we can see that the return result is the division part and the remainder part, in a tuple.

19. enumerate ()

Enumerate () adds an order to the list. The instance is as follows:

>>> L1 = ["alex", "aoi", "eric", "tom"]
>>> For item, I in enumerate (l1, 1 ):
... Print (item, I)
...
1 alex
2 aoi
3 eric
4 tom
>>> For item, I in enumerate (l1, 1 ):
... Print (item)
...
1
2
3
4
>>> For item, I in enumerate (l1, 1 ):
... Print (I)
...
Alex
Aoi
Eric
Tom

We can see that using the enumerate () function can add an order to the list. We know that the index position of the list starts from 0, but people are used to starting from 1, therefore, the order of commodities in the website also starts from 1. Therefore, you need to use enumerate () to define a starting index position. Similar to the dictionary function, numbers represent keys, and values in the list represent values.

20. eval ()

Eval () is a mathematical algorithm that converts string format algorithms. We know that in Python, 6*8 = 24, however, if we write "6*8", this form is a string and cannot represent the result. Eval ("6*8") is an expression that converts a arithmetic expression in the text form to a string format.

Example:

>>> A = 6*8
>>>
48
>>> B = "6*8"
>>> B
'6*8'
>>> Eval (B)
48
From the above example, we can see that eval () is used for string expression operations. In Excel, there are also such functions. The macro function evaluate () can also implement this function.

21. exac ()

22. filter ()

Filter () is used for filtering. Return the results that meet the conditions. Otherwise, filter them out.

>>> Li = [11, 22, 33, 44]
>>> Def func (x ):
... If x> 33:
... Return True
... Else:
... Return False
>>> List (filter (func, li ))
[44]

Filter () is the meaning of word filter. filter elements in a sequence to obtain a sequence that meets the criteria.

In the preceding figure, we use the filter () function to filter two elements that do not meet the conditions.

23. map ()

Map () and filter () are used to filter functions, and map () is used to generate the same element. For each value in the map (function, list) loop list, the parameter is passed to the Change number for a loop. Example:

Lambda expressions:

>>> Li = [11,22, 33,44]
>>> Map (lambda a: a + 100, li)
<Map object at 0x7f5135f24208>
>>> List (map (lambda x: x + 1, li ))
[12, 23, 34, 45]
Function:

>>> Li = [11, 22, 33, 44]
>>> Def func (x ):
... X = x + 1
... Return x
...
>>> Map (func, li)
<Map object at 0x7f5135f24240>
>>> List (map (func, li ))
[12, 23, 34, 45]
Map () is a traversal sequence. Each element in the sequence is operated to obtain a new sequence. For example:

 24. float ()

Float () converts a number to a floating-point format, but the floating-point format occupies memory. Use as few as possible.
25. format ()

The format () method is similar to the _ format _ () method.

26. frozenset ()

Freeze and modify the set. We know that the set can be modified, but the frozenset () is used to freeze the set so that the set cannot be modified. Example:

>>> Import collections
>>> Users = frozenset ([11,22, 33,44])
>>> Names = set (["alex", "sb", "tom", "albom", "dvda"])
>>> Names. pop ()
'SB'
>>> Users. pop ()
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'pop'
In the code above, we defined two sets, one being a normal set, and the other being a frozen set using frozenset (). set () can be deleted, but frozenset () cannot be deleted.

27. getattr ()

28. globals ()

All currently available global variables of globals (), output all currently available global variables.

29. hasatter ()

30. hash ()

31. help ()

32. hex ()

The hex () function is used to convert numbers into Hexadecimal notation, and hex is the abbreviation of the Hexadecimal notation. The following is a simple example.

>>> Hex (17)
'0x11'
>>> Hex (10)
'0xa'
>>> Hex (12)
'0xc'

31. input ()

Input () user input function, prompting user input information.

32. id ()

33. int ()

32. isintance ()

33. issubclass ()

34. len ()

35. list ()

36. locals ()

All local variables of locals.

37. max ()

Max () maximum function.

38. min ()

Min () Minimum value function.

39. memoryview ()

40. object ()

41. oct ()

Oct () octal function, which converts numbers to octal values. In the oct () function, oct stands for the word Octal number system, representing Octal. A simple example is as follows:

>>> Oct (12)
'0o14'
>>> Oct (0)
'0o0'
>>> Oct (8)
'0o10'
42. open ()

The open () function is used to open a file.

43. pow ()

The pow () function is a struct function. A simple example is as follows:

>>> Pow (2, 3)
8
>>> Pow (3, 2)
9
Pow (2, 3) is equivalent to 2 ** 3. Power 3 of 2.

44. print ()

Print () is used to print the output value.

45. property ()

46. range ()

Range () creates a region. Range () is equivalent to creating a list. It is created only when the for loop is used to save space.

47. repr ()

48. reversed ()

Reversed () is used to reverse the list.

49. round ()

The round () Rounding function is used for rounding. Example:

>>> Round (3.8)
4
>>> Round (2.1)
2
>>> Round (-3.8)
-4

50. set ()

Set () is used to create a set. The set is unordered. Unique.

51. setatter ()

Setatter () is used for slicing.

52. slice ()

53. sorted ()

Sorted.

54. staticmethod ()

Static Methods in the staticmethod () class.

55. str ()

Str () is converted to a string function, short for string.

56. sum ()

Sum () List summation function.

57. super ()

Super () super parent class.

58. tuple ()

Tuple () is converted into a tuples.

59. type ()

60. vars ()

61. zip ()

Zip () is used to generate coordinates. Combine the elements of the two lists and put them in the list to form a list. A simple example is as follows:

>>> X = [11, 22, 33]
>>> Y = [44,55, 66]
>>> Z = [77, 88, 99]
>>> X_y = zip (x, y)
>>> X_y
<Zip object at 0x7f35c3d3e988>
>>> List (x_y)
[(11, 44), (22, 55), (33, 66)]
>>> X_y_z = list (zip (x, y, z ))
>>> X_y_z
[(11, 44, 77), (22, 55, 88), (33, 66, 99)]

62. _ import __()

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.