Home Backend Development Python Tutorial What are the commonly used functions in python?

What are the commonly used functions in python?

Jul 23, 2019 am 11:01 AM
python function

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]
Copy after login

s.format() is a new method used to format characters. The example is as follows:

s = 'I am {0}{1}'
print s.format('liheng','!')
Copy after login

Output results:

 I am liheng!
Copy after login

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
Copy after login

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)
Copy after login

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])
Copy after login

•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
Copy after login

Then, use filter() to filter out even numbers:

filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
Copy after login

Result:

[1, 7, 9, 17]
Copy after login
#利用过滤函数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)
Copy after login

or

import math
def is_sqr(x):
  r = int(math.sqrt(x))
  return r*r==x
print filter(is_sqr, range(1, 101))
Copy after login

•Custom sorting function

Python The built-in sorted() function can sort the list:

>>>sorted([36, 5, 12, 9, 21])
[5, 9, 12, 21, 36]
Copy after login

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
Copy after login

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]
Copy after login

sorted() can also sort strings. Strings are compared according to ASCII size by default:

>>> sorted([&#39;bob&#39;, &#39;about&#39;, &#39;Zoo&#39;, &#39;Credit&#39;])
[&#39;Credit&#39;, &#39;Zoo&#39;, &#39;about&#39;, &#39;bob&#39;]
Copy after login

'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 = [&#39;bob&#39;,&#39;about&#39;,&#39;Zoo&#39;,&#39;Credit&#39;]
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)
Copy after login

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 = &#39;sys&#39;
model = __import__(temp)
foo = &#39;path&#39;
function = getattr(model,foo)
print function
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles