Python practical unpopular knowledge sorting

Posted by GreenCore on Mon, 07 Mar 2022 15:51:02 +0100

1.print print information with color

You know the print function in Python. Generally, we will use it to print something as a simple debugging.

But you know, the font color printed by Print can be set.

A small example

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

After running this code on the console or pychar, you will get the results.

Error:important

Where Error is underlined in red and important is the default color

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

The following parameters can be set:

explain:

Foreground background color
---------------------------------------
30 40 black
31 41 gules
32 42 green
33 43 Yellow
34 44 blue
35 45 Purplish red
36 46 Turquoise blue
37 47 white
 Display mode and meaning
-------------------------
0 Terminal default settings
1 Highlight
4 Use underline
5 twinkle
7 Anti white display
8 invisible

example:

\033[1;31;40m <!--1-Highlight 31-Foreground red 40-Background color black-->

2. Using timers in Python

Today I saw a more user-friendly timing module schedule. At present, the number of star s is 6432, which is still very popular. This module also adheres to the principle of For Humans and is recommended to you here. address https://github.com/dbader/schedule

1. It can be installed through pip.

pip install schedule

2. Use cases

'''
No one answers any questions? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
import schedule
import time
def job():
 print("I'm 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 does.

for instance:

schedule.every().monday.do(job)

The function of this code is the meaning of the word. The timer will run the function job every Monday. Is it very simple.

3. Achieve a progress bar

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

Display effect

The print in the above code has several useful parameters. The function of sep is to use what is a separator. The default is a space. Here, it is set as an empty string to make each character more compact. The function of end parameter is what is the end. The default is a carriage return line feed. Here, it is also set as an empty string to achieve the effect of progress bar. There is also the last parameter flush, which is mainly used to refresh. The default flush = False. Do not refresh. The contents from print to f are stored in memory first; When flush = True, it will immediately refresh and output the content.

Previously, download the tqdm module mentioned in xiamu friends account in Python to better realize a progress bar

4. Print nested data gracefully

We should all have the impression that when printing json strings or dictionaries, there is no hierarchical relationship between the printed things. What we mainly talk about here is the problem of output format.

import json
my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
print(json.dumps(my_mapping, indent=4, sort_keys=True))

You can try it yourself and print my with print only_ Mapping, and examples of this printing method.

If we print the list composed of dictionaries, it's certainly not possible to use the dumps method of json at this time, but it doesn't matter

The above method can also be implemented with the pprint method of the standard library

import pprint
my_mapping = [{'a': 23, 'b': 42, 'c': 0xc0ffee},{'a': 231, 'b': 42, 'c': 0xc0ffee}]
pprint.pprint(my_mapping,width=4)

5. Classes with simple functions are defined by namedtuple and dataclass

Sometimes when we want to implement a function similar to a class, but there are not so complex methods to operate, we can consider the following two methods at this time.

First, named tuple, also known as named tuple, is a tuple with a name. As a module in Python standard library collections, it can realize a function similar to a class.

'''
No one answers any questions? Xiaobian created a Python exchange of learning QQ Group: 1509025
 Look for like-minded partners to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
from collections import namedtuple
# Previously, simple classes could be implemented using namedtuple.
Car = namedtuple('Car', 'color mileage')
my_car = Car('red', 3812.4)
print(my_car.color)
print(my_car)

However, all 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 could 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 Python 3 7 data class added to the standard library.

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

Examples of use are as follows:

from dataclasses import dataclass
@dataclass
class Car:
 color: str
 mileage: float
my_car = Car('red', 3812.4)
print(my_car.color)
print(my_car)

6.f-string! r,!a,!s

F-string appears in Python 3 6. As the best form of splicing string at present, take a look at the structure of f-string

f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '

Of which '! s' calls str(), '! r 'calls repr () on the expression,'! a 'call ascii() on the expression

(1) By default, f-string s will use str(), but if you include conversion flags, you can ensure that 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"{new_comedian!r}"
'Eric Idle is 74. Surprise!'

(2) ! Example of a

'''
Did anyone answer the question? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded partners to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
>>> a = 'some string'
>>> f'{a!r}'
"'some string'"

Equivalent to

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

(3) !d example

Similar 2

pycon2019 someone put forward a prospect! d function realization:


In Python 3 The above functions have been realized in 8, but they are no longer used! d changed to f"{a =}". Have you seen this video! d should be confused

7. Application of "=" in f-string

In Python 3 There is such a function in 8

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

The result after printing is

a=5

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

8. Walrus operator: = use

a =6
if (b:=a+1)>6:
 print(b)

The assignment can be operated at the same time, which is similar to the assignment of Go language.

For the running sequence of the code, first calculate a+1 to get the value of 7, and then assign 7 to b. here, the code is equivalent to the following

b =7
if b>6:
 print(b)

Topics: Python Programming