Home >Backend Development >Python Tutorial >What are the commonly used functions in python?
Python commonly used functions:
1. print() function: print a string
2. raw_input() function: capture characters from the user keyboard
3. len() function: calculate character length
4. format(12.3654, '6.2f'/'0.3%') function: implement formatted output
5. type () function: query the type of object
6. int() function, float() function, str() function, etc.: type conversion function
7. id() function: get The memory address of the object
8. help() function: Python’s help function
9. s.islower() function: determine the lowercase character
10. s.sppace () function: determine whether it is a space
11. str.replace() function: replace the character
12. import() function: import the library
13. math. sin() function: sin() function
14. math.pow() function: calculate the power function
15. 3**4: 3 to the fourth power
16. pow(3,4) function: 3 raised to the fourth power
17. os.getcwd() function: get the current working directory
18. listdir() function: display Files in the current directory
19. socket.gethostbyname() function: Get the IP address of a host
20. urllib.urlopen(url).read(): Open network content and store it
21. open().write() function: write a file
22. webbrowser.open_new_tab() function: create a new tab and use the browser to open the specified web page
23. def function_name(parameters): Custom function
24. time.sleep() function: stop for a period of time
25. random.randint() function: generate random numbers
26. range() function: returns a list, printing from 1 to 100
27. file.read() function: reads the file and returns a string
28. file .readlines() function: read a file and return a list
29. file.readline() function: read a line of file and return a string
30. ords() and chr(ASCII) Function: Convert a string to ASCII or ASCIIS\ to a string
31. find(s[,start,end]) function: Find s
32 from a string. strip(), lstrip(), rstrip() function: remove spaces
33. split() function: what to use to separate strings
34. isalnum() function: determine whether it is Valid numbers or characters
35. isalpha() function: determine whether all characters are characters
36. isdigit() function: determine whether all are numbers
37. lower () function: change the data to lowercase
38. upper() function: change the data to uppercase
39. startswith(s) function: determine whether the string starts with s
40. endwith(s) function: determine whether the string ends with s
41. file.write() function: write function
42. file.writeline () function: write to file
43. s.append() function: insert data at the end of the data
44. s.insert(3,-1) function: at 3 Insert data before the position -1
45. list() function: convert the string into a list
46. index(value) function: find the position of the first value in the data
47. list.extend() function: extract each piece of data and add it to the list
48. count() function: count the number of occurrences of a certain element in the data
49. list.remove("s") function: delete the first occurrence of s in the data
50. del list[2] function: delete the second element of the data
51. pop() function: remove the data at the specified position of the data, with a return value
52. remove("ha") function: remove the "ha" element in the original data
53. reverse() function: reverse order of the list
54. isinstance() function: determine whether a certain data is of a certain type
55. abs() function: Get the absolute value of a number
56. del x[2] function: delete the element with index 2 in list x
57. file.sort() function: sort the book data
58. tuple() function: Create a tuple
59. find() function: The search returns the index
60. join() function: split Reverse operation
61. { }: Create a dictionary
62. dict() function: Create a dictionary
63. clear() function: Clear all items in the dictionary
64. copy() function: copying a dictionary will modify all dictionaries
65. d.copy() function: copying a dictionary will only modify the current dictionary
66. get() function: Query elements in the dictionary
67. items() function: Return all dictionaries into a list
68. iteritems() function: Function with items function Same
69. popitem() function: remove elements from the dictionary
70. update() function: update one dictionary item with another dictionary item
71. pass: do nothing
72.exec: execute a piece of code
73.eval: calculate Python expression
74.ord() function: return a single character The int value of the string
75.zip(sep1, sep2) function: Create a new sequence of English parallel iteration
76.def hello(): Custom function
77.import() function: Load extension library
Related recommendations: "Python Tutorial"
Several commonly used built-in functions commonly used in Python:
abs(x) is used to return the absolute value
divmod(x,y) The function passes two numbers and returns a tuple of the result of x/y (quotient , remainder)
pow(x,y) is used to find the y power of x
all(iterable) An iterable object is passed into the function. If all the numbers in the object True will be returned only if all bool values are true, otherwise it will return False
any(iterable) passes an iterable object into the function. If the bool value of a number in the object is true, True will be returned. If all numbers are 0, False will be returned.
chr (x) Pass in an ascii code to the function, convert the ascii into the corresponding character
ord(x) Pass in a character into the function, convert the character into the corresponding ascii code
hex () Hexadecimal
oct() Octal
bin() Binary
enumerate(x,y) The x passed in the function is a list , y is the initial value of the iteration, such as the following example:
li = ['baby','honey'] for item in li: print item for item in enumerate(li,12): print item for item in enumerate(li,13): print item[0],item[1]
s.format() is a new method used to format characters. The example is as follows:
s = 'I am {0}{1}' print s.format('liheng','!')
Output results:
I am liheng!
Combined use of map() and lambda function map(lambda,list)
•reduce() function
reduce() function is also a high-level built-in Python function. The parameters received by the reduce() function are similar to map(), a function f and a list, but the behavior is different from map(). The function f passed in by reduce() must receive two parameters. reduce() evaluates each element of the list. The element calls function f repeatedly and returns the final result value.
For example, write a function f that receives x and y and returns the sum of x and y:
def f(x, y): return x + y
Call reduce(f, [1, 3, 5, 7, 9 ]), the reduce function will do the following calculations:
First calculate the first two elements: f(1, 3), the result is 4;
Then calculate the result and the third element : f(4, 5), the result is 9;
Then calculate the result and the 4th element: f(9, 7), the result is 16;
Then calculate the result and the 4th element Calculation of 5 elements: f(16, 9), the result is 25;
Since there are no more elements, the calculation ends and the result 25 is returned.
The above calculation is actually the sum of all elements of list. Although Python has a built-in summation function sum(), it is also very simple to use reduce() to sum.
reduce() can also receive a third optional parameter as the initial value for calculation. If the initial value is set to 100, the calculation:
reduce(f, [1, 3, 5, 7, 9], 100)
The result will become 125, because the first round of calculation is:
Calculate the initial value and the first element: f( 100, 1), the result is 101.
Code block using reduce() for continuous multiplication
def f(x,y): return x * y print reduce(f,[2,4,5,7,12])
•filter() function (filter function)
filter() function is Python Another useful built-in high-order function, the filter() function receives a function f and a list. The function of this function f is to judge each element and return True or False. filter() automatically filters out incorrect elements based on the judgment result. Elements that meet the criteria return a new list consisting of elements that meet the criteria.
For example, to delete even numbers and keep odd numbers from a list [1, 4, 6, 7, 9, 12, 17], first, write a function to determine odd numbers:
def is_odd(x): return x % 2 == 1
Then, use filter() to filter out even numbers:
filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
Result:
[1, 7, 9, 17]
#利用过滤函数filter()进行删除None和空字符串 def is_not_empty(s): return s and len(s.strip()) > 0 l = ['test','str',None,'','','END'] print filter(is_not_empty,l) # 利用函数filter()过滤出1~100中平方根是整数的数 import math l = [] for x in range(1,101): l.append(x) def is_int(x): r = int(math.sqrt(x)) return r * r == x print filter(is_int,l)
or
import math def is_sqr(x): r = int(math.sqrt(x)) return r*r==x print filter(is_sqr, range(1, 101))
•Custom sorting function
Python The built-in sorted() function can sort the list:
>>>sorted([36, 5, 12, 9, 21]) [5, 9, 12, 21, 36]
But sorted() is also a higher-order function. It can receive a comparison function to implement custom sorting. The definition of the comparison function is, Pass in two elements x and y to be compared. If x should be ranked in front of y, return -1. If x should be ranked after y, return 1. If x and y are equal, return 0.
Therefore, if we want to implement reverse sorting, we only need to write a reversed_cmp function:
def reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 return 0
In this way, calling sorted() and passing in reversed_cmp can achieve reverse sorting :
>>> sorted([36, 5, 12, 9, 21], reversed_cmp) [36, 21, 12, 9, 5]
sorted() can also sort strings. Strings are compared according to ASCII size by default:
>>> sorted(['bob', 'about', 'Zoo', 'Credit']) ['Credit', 'Zoo', 'about', 'bob']
'Zoo' is ranked before 'about' because of 'Z' The ASCII code is smaller than 'a'.
When sorting strings, sometimes it is more customary to ignore case sorting. Please use the sorted() high-order function to implement an algorithm that ignores case sorting.
l = ['bob','about','Zoo','Credit'] def cmp_ignore_case(s1,s2): u1 = s1.upper() u2 = s2.upper() if u1 < u2: return -1 if u1 > u2: return 1 return 0 print sorted(l,cmp_ignore_case)
zip() Introduction to the use of function
eval(str) The function can convert str into an expression for execution
__import__ and getattr() The use of
#以字符串的形式导入模块和函数 temp = 'sys' model = __import__(temp) foo = 'path' function = getattr(model,foo) print function
The above is the detailed content of What are the commonly used functions in python?. For more information, please follow other related articles on the PHP Chinese website!