Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the 8 most commonly used built-in functions necessary for Python

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What are the eight most commonly used built-in functions necessary for Python? this article describes in detail the corresponding analysis and solutions to this problem, hoping to help more partners who want to solve this problem to find a simpler and easier way.

Python gives us a large number of built-in functions, 69 of which are listed in the official documents, some of which we often encounter in our development, and some of which are rarely used. Here are the 8 functions most frequently used by developers and their detailed usage.

Print ()

The print function is the * function you learn from Python. It outputs objects to the standard output stream and can print out any number of objects. The specific definition of the function:

Print (* objects, sep='', end='\ nkeeper, file=sys.stdout, flush=False)

Objects is a variable parameter, so you can print out any number of objects at the same time

> print (1, 2, 2, 3) 1 2 3

Each object is separated by default with spaces, and can be separated by commas by specifying the sep parameter.

> print (1, sep=',', 2) 1, 2, 3

The default output of the object is the standard output stream, or you can save the content to a file

> print (1, 2, 3, sep=',', file=open ("hello.txt", "w"))

Isinstance ()

You can use the isinstance function to determine whether an object belongs to an instance of a class and the definition of the function.

Isinstance (object, classinfo)

Classinfo can be either a single type object or a tuple of multiple type objects. True is returned as long as the type of object is any one of the tuples, otherwise False is returned.

> isinstance (1, (int, str)) True > isinstance ("", (int, str)) True > isinstance ([], dict) False

Range ()

The range function is a factory method that is used to construct a continuous and immutable integer sequence object from [start, stop) (excluding stop). This sequence is very similar to a list in function definition:

Range ([start,] stop [, step])-> range object

Start optional parameter, the starting point of the sequence. Default is 0.

Stop required parameter, the end of the sequence (not included)

Step optional parameter. The step size of the sequence is 1 by default, and the generated element rule is r [I] = start + step*i.

Generate a list of 05s

> range (5) range (0,5) > list (range (5)) [0,1,2,3,4] >

By default, starting from 0, 5 integers between 0 and 4 are generated, excluding 5, and the default step is 1, each time adding 1 to the previous one.

If you want to repeat an operation n times, you can use the for loop to configure the range function to implement

For i in range (3):... Print ("hello python")... Hello python

Step size is 2

> range (1,10,2) range (1,10,2) > list (range (1,10,2)) [1,3,5,7,9]

The starting point is 1, the end is 10, and the step size is 2. Each time, 2 is added to the previous element to form an odd number between 1 and 10.

Enumerate ()

Used to enumerate iterable objects, you can also get the following table index value of each element, function definition:

Enumerate (iterable, start=0)

For example:

For index, value in enumerate ("python"):... Print (index, value)... 0 p 1 y 2 t 3 h 4 o 5 n

Index starts from 0 by default, and if the parameter start is explicitly specified, the subscript index starts from start.

For index, value in enumerate ("python", start=1):... Print (index, value)... 1 p 2 y 3 t 4 h 5 o 6 n

If you don't use the enumerate function, you need more code to get the subscript index of the element:

Def my_enumerate (sequence, start=0): n = start for e in sequence: yield n, en + = 1 > for index, value in my_enumerate ("python"): print (index, value) 0 p 1 y 2 t 3 h 4 o 5 n

Len

Len is used to obtain the number of elements in the container object. For example, you can use the len function to determine whether the list is empty.

> len ([1 python 2) 3] 3 > > len ("python") 6 > if len ([]) = = 0: pass

Not all objects support len operations, for example:

> len (True) Traceback (most recent call last): File ", line 1, in TypeError: object of type 'bool' has no len ()

In addition to sequence objects and collection objects, the custom class must implement the _ _ len__ method to act on the len function

Reversed ()

Reversed () reverses the sequence object, you can reverse the string, reverse the list, reverse the tuple

> list (reversed ([1jin2jin3])) [3,2,1]

Open ()

The open function is used to construct a file object, which can be read and written to its contents after construction.

Open (file, mode='r', encoding=None)

Read operation

# Open the file test.txt from the current path, default to read > f = open ("test.txt") > f.read ().

Sometimes you also need to specify the coding format, otherwise you will encounter garbled codes.

F = open ("test.txt", encoding='utf8')

Write operation

> f = open ("hello.text", 'hello python, encoding='utf8') > f.write ("hello python"))

When there is content in the file, the original content will not be overwritten. If you do not want to be overwritten, append the new content directly to the end of the file. You can use a mode.

F = open ("hello.text", 'averse, encoding='utf8') f.write ("!!")

Sorted ()

Sroted is to reorder the list. Of course, other iterable objects support rearrangement. A new object is returned, and the original object remains unchanged.

> sorted ([1, 4, 2, 1, 0]) [0,1,1,2,4]

There are many more advanced uses of sorted.

The answers to the eight most commonly used built-in functions of Python are shared here. I hope the above can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report