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 interesting tips for using Python?

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what are the interesting skills for using Python". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

One. Print prints information with color

We all know that the information printing function Print in Python, usually we will use it to print something as a simple debugging.

But did you know that the font color printed by this Print can be set?

A small example

Def esc (code=0): return f'\ 033 [{code} m'print (esc) + 'Error:'+esc () +' important')

You will get the results after running this code on the console or Pycharm.

Error:important

Error is red and underlined, and important is the default color.

The format is:\ 033 [display mode; foreground color; background color m

The following parameters can be set:

Description: foreground color background color-30 40 black 31 41 red 32 42 green 33 43 blue 34 44 blue 35 45 purplish red 36 46 cyan 37 47 white display meaning End default setting 1 highlight 4 use underscore 5 flicker 7 highlight 8 invisible example:\ 033 [1 31x 40m 2. Using timers in Python

Today, I see a more humanized timing module schedule. At present, the number of star is 6432, which is still very popular. This module also adheres to the principle of For Humans.

1. It can be installed through pip.

Pip install schedule

two。 Use case

Import scheduleimport timedef job (): print ("Ilemm working...") schedule.every (10) .minutes.do (job) schedule.every (). Hour.do (job) schedule.every (). Day.at ("10:30") .do (job) schedule.every (). Monday.do (job) schedule.every (). Wednesday.at ("13:15") .do (job) schedule.every (). Minute.at ("17") .do (job) while True : schedule.run_pending () time.sleep (1)

From the literal meaning of the word, you know what it is for.

For example:

Schedule.every () monday.do (job)

This code function is the meaning of the word, the timer will run the function job every Monday, how is it very simple?

Three. Implement a progress bar from time import sleepdef progress (percent=0, width=30): left = width * percent / / 100right = width-left print ('\ r [','#'* left,'* right,']', f' {percent:.0f}%', sep='', end='', flush=True) for i in range: progress (I) sleep

Display effect

Stop shit and try it quickly.

The print in the above code has several useful parameters. The role of sep is what is the delimiter. The default is a space. Here, it is set to an empty string to make each character more compact. What is the end of the end parameter? the default is the enter newline character. Here, in order to achieve the effect of the progress bar, it is also set to an empty string. There is also the last parameter flush, which is mainly used to refresh. The default is flush = False. If it is not refreshed, the contents of print to f will be stored in memory first; when flush = True, it will immediately refresh and output the contents.

Previously in the Python download Xia Mu friend account mentioned hungry tqdm module, a better implementation of a progress bar.

Four. Elegantly print nested data

Everyone should have the impression that when printing json strings or dictionaries, there is no hierarchical relationship between a bunch of things printed out. Here we are mainly talking about the output format.

Import jsonmy_mapping = {'averse: 23,' baked: 42, 'clockwise: 0xc0ffee} print (json.dumps (my_mapping, indent=4, sort_keys=True))

You can try this printing method of using only print to print my_mapping, and examples.

If we print a list of dictionaries, it certainly won't work to use json's dumps method at this time, but it doesn't matter.

The above method can also be implemented by using the pprint method of the standard library.

Import pprintmy_mapping = [{'averse: 23,' baked: 42, 'cased: 0xc0ffee}, {' averse: 231, 'baked: 42,' cased: 0xc0ffee}] pprint.pprint (my_mapping,width=4) V. Classes with simple functions are defined using namedtuple and dataclass

Sometimes when we want to implement a class-like function, but there are less complex methods to operate, we can consider the following two methods.

The first, namedtuple, is also called a named tuple, a tuple with a name. As a module in the Python standard library collections, it can achieve a function similar to a class.

From collections import namedtuple# previously simple classes can be implemented using namedtuple. Car = namedtuple ('Car',' color mileage') my_car = Car ('red', 3812.4) print (my_car.color) print (my_car)

However, all the attributes need to be defined in advance before they can be used. For example, if you want to use my_car.name, you have to change the code to look like this.

From collections import namedtuple# previously simple classes can be implemented using namedtuple. Car = namedtuple ('Car',' color mileage name') my_car = Car ('red', 3812.4, "Auto") print (my_car.color) print (my_car.name)

The disadvantages of using namedtuple are obvious.

So now the better solution is to add Python3.7 to the dataclass of the standard library.

In fact, it can also be used in 3.6, but it needs to be used as a third-party library, it can be installed using pip.

Examples of use are as follows:

From dataclasses import dataclass@dataclassclass Car: color: str mileage: floatmy_car = Car ('red', 3812.4) print (my_car.color) print (my_car) six. F-string! r _ 7 _ r _ r

F-string appears in Python3.6, as the current best form of concatenating strings, take a look at the structure of f-string

F'{}.'

Where'! s' calls str () on the expression,'! R' calls repr () on the expression, and'! a 'calls ascii () on the expression.

(1. By default, f-string uses str (), but if you include conversion flags, you can make sure they use repr ()!

Class Comedian: def _ init__ (self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def _ str__ (self): return f "{self.first_name} {self.last_name} is {self.age}." Def _ _ repr__ (self): return f "{self.first_name} {self.last_name} is {self.age} .Surprise!"

Call

> new_comedian = Comedian ("Eric", "Idle", "74") > f "{new_comedian}" 'Eric Idle is 74.' > f "{new_comedian}"' Eric Idle is 74.' > > f "{newcomedianonymr}" 'Eric Idle is 74. Surpriseholders'

(2.Example of Secreta

> a = 'some string' > f' {axir}' "'some string'"

Equivalent to

> f' {repr (a)}'"'some string'"

(3.Example of Secretd

Similar to 2

A prospect put forward by someone in pycon2019! d's function implementation:

The above functions have been implemented in python3.8, but no longer used! d has been changed to the form of f "{a =}". Have you seen this video? d should be confused.

Seven. The Application of "=" in f-string

There is such a function in Python3.8

A = 5print (f "{a =}")

The result after printing is

Axi5

Is it very convenient? you don't have to use f "a = {a}" anymore.

Eight. The walrus operator: = uses a = 6if b:=a+1 > 6: print (b)

Assignment can be performed at the same time, which is similar to the assignment in Go language.

The running order of the code, first calculate axi1 to get a value of 7, and then assign 7 to b, so here the code is equivalent to the following

B = 7if b > 6: print (b) this is the end of the content of "what are the interesting tips for using Python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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