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 Python tips

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what are the Python tips". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what Python tips"!

1. F-Strings

F-Strings provides an easy way to embed Python expressions in string text for formatting. First, define two variables that will be used in the print statement: name and age.

Name = "Pavel" age = 23

In order not to handle string concatenation or to use commas in print statements, you can use the Python3.6 upgrade string formatting method "f-Strings". Simply precede a string with a variable or expression in curly braces with a lowercase or uppercase letter "f".

F-Strings is a great new way to format strings, and the results are more readable, faster, more concise, and less error-prone.

two。 Find the size of any object

The default sys module contains a getsizeof function that takes an object and returns its size in bytes. The object can be of any type. For example:

Only calculate the memory consumption directly attributed to the object, not the memory consumption of the object it refers to. Let's look at another example:

3. Exchange variables in situ

In many other programming languages, the values of two or more variables can be exchanged only by defining an additional temp (temporary) variable. Suppose you want to exchange x and y:

Temp = x x = y y = temp

Python uses a simple single-line structure to exchange variables, similar to the concept of assigning values to multiple variables in a row. The following code is the same as above, but does not use any temporary variables:

4. Links to compare operators

Typically, when you want to check more than two conditions, you must use a logical operator, such as and/or:

If a < b and b < c:

In Python, there is a better way to write it using comparison operator linking. The chain of operators can be written as follows:

If a < b < c:

For example:

5. List understanding

List understanding is a more common and ingenious way of making lists. Instead of creating an empty list and adding each element to the end, just define the list and its contents in the following format:

New_list = [expression for item in iterable (if conditional)]

For example:

Another example (conditional):

6. String multiplication

In Python, you can multiply not only by numbers, but also by strings. For example:

7. Assign multiple variables in a row

Variables and values can be separated by commas, thus assigning multiple values to each variable:

This also applies when deconstructing / unpacking a sequence, such as a list or tuple, and assigns the elements of the sequence to individual variables more cleverly, because there is no need to use loops or individually index each element in the sequence.

8. Parameter unpacking

The Splat or Scatter operator * sometimes comes into play when you need to unpack parameters in a list or tuple for function calls that require separate positional arguments.

For example, the built-in range () function requires separate start and stop parameters. When writing function calls, you can use the * operator to unpack parameters from a list or tuple:

Let's define a simple list: X = [1, 2, 3, 4, 5].

A common example of unpacking operators is using print:

Print (* x) / / Result: 1 2 3 4 5

This simply prints out each element in the list, separated by spaces, because the unpacking operator accepts all the elements in the list and passes them as parameters, so the above code is converted to print (1meme, 2meme, 3mem4p5).

This Python technique is often used in functions to 'package' all the parameters received by the method call into a single variable. For example:

The above function func can accept an unlimited number of arguments (args [0] and args [1] will provide the first and second arguments, respectively).

In a similar manner, dictionaries can use the * operator to pass keyword parameters. To define a Python dictionary named person:

Person = {"name": "Paul", "age": 23, "location": "London"}

You can use the * operator to pass the dictionary to the function. The incoming dictionary decomposes the keys into a function keyword parameter, which is then taken as the actual value passed for that parameter. For example:

9. Create Enum

Enum is the class used to create enumerations in Python, and enumerations are a set of symbolic names attached to unique constant values.

In order to create an Enum, you must create a class that is the name of the desired Enum. All that's left to do is list the variable and set it to the desired value:

To access the enumeration member Paul, for example, simply execute Person.Paul, which returns 0. In Python, you can simplify the above example by listing variables next to each other and setting them equal to the range function:

10. Enumerate

Typically, when traversing a list, you access not only all the indexes in the list, but also the actual elements. To define a list of characters:

X = ['await,' baked,'c']

Instead of traversing it in a standard way, access elements and indexes:

Use Enumerate:

Enumerate is the built-in function of Python, which allows us to loop through an iterable object and has an automatic counter. In fact, it matches each element in the list with the corresponding index, which is unknown to most newcomers and even some senior programmers.

You can change the variables I and v to your favorite variable name. For example, for index, count in enumerate (x)..

11. Help function

The Python help function is used to find help documentation for modules, functions, classes, keywords, and so on. Simply pass an object in the help function to retrieve the help documentation for that object:

12. Dir function

Dir () is a powerful built-in function in Python3 that returns a list of properties and methods for any object (that is, functions, modules, strings, lists, dictionaries, and so on). This is useful when there is little information about the module and helps you learn new modules faster. For example:

Dir () is usually used for debugging purposes. Dir () is able to list all the attributes that pass parameters, which is useful when dealing with many classes and functions separately.

Thank you for your reading, the above is the content of "what Python tips", after the study of this article, I believe you have a deeper understanding of what Python tips are, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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