1. Print Prints colored information

You know the information printing function in Python, print, and we usually use it to print something as a simple debugging.

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

A little example

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

After running this code on the console or Pycharm, you will get the result.

Error:important
Copy the code

Error is underlined in red and important is the default color

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

The following parameters can be set:

Description: Foreground color background color

---------------------------------------
30 40black31 41red32 42green33 43yellow34 44blue35 45purple36 46Green, blue37 47whiteCopy the code

Significance of display mode

-------------------------
0Terminal Default Settings1The highlighted4Use underscores5flashing7The white shows8invisibleCopy the code

Example:

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

2. Use timers in Python

Today, I saw a humanized schedule module. Currently, the star number is 6432, which is still very popular. This module also adheres to the principle of For Humans, which is recommended here. Address github.com/dbader/sche…

1. You can install it using PIP.

pip install schedule
Copy the code

Use cases

"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
import schedule
import time
def job(a):
 print("I'm working...")
schedule.every(10).minutes.do(job) 
schedule.every().hour.do(job)
schedule.every().day.at("At 10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("Anyone").do(job)
schedule.every().minute.at(", 17").do(job)
while True:
 schedule.run_pending()
 time.sleep(1)
Copy the code

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

Here’s an example:

schedule.every().monday.do(job)
Copy the code

The timer will run the job function every Monday.

3. Implement a progress bar

"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
from time import sleep
def progress(percent=0, width=30):
 left = width * percent // 100
 right = width - left
 print('\r['.The '#' * left, ' ' * right, '] '.f' {percent:. 0f}% ',
 sep=' ', end=' ', flush=True)
for i in range(101):
 progress(i)
 sleep(0.1)
Copy the code

Display effect

Flush = False; flush = False; print to f; When flush = True, it immediately flushs and prints.

The TQDM module mentioned in the previous Python download is a better implementation of a progress bar.

4. Gracefully print nested types of data

If you’re printing a JSON string or dictionary, there’s no hierarchy at all, and it’s all about the output format.

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

You can try printing my_mapping with print only.

What if we were to print a list of dictionaries, the DUMPS method of JSON would not work at this point, but that’s ok

You can do the same with the library’s pprint method

"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
import pprint
my_mapping = [{'a': 23.'b': 42.'c': 0xc0ffee}, {'a': 231.'b': 42.'c': 0xc0ffee}]
pprint.pprint(my_mapping,width=4)
Copy the code

5. Simple classes are defined using Namedtuple and dataclass

Sometimes we want to implement a similar class function, but there is not that complex method to operate, this time can consider the following two methods.

The first one, namedtuple, also known as a namedtuple, is a tuple with a name. It is a module in the Python standard library Collections that implements a function of a similar class.

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)
Copy the code

However, all attributes need to be defined in advance. For example, to use my_car.name, you need to change the code to look like this.

"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
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)
Copy the code

The disadvantages of using namedTuple are obvious.

So a better solution now is to add Dataclass to the standard library.

It is also available in 3.6 but requires it to be used as a third party library, using PIP installation.

The following is an example:

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

6. F – string! r,! a,! s

F-string appears in Python3.6 as the current best concatenated string form. Take a look at the structure of f-string

f ' 
      
        { 
        
         
         
           } 
          
            ... '
          
         
        
       
      
Copy the code

The ‘! S ‘calls STR () on the expression, ‘! R ‘calls repr () on the expression, ‘! A ‘calls ASCII () on expression

(1) By default, f-strings will use STR (), but if conversion flags are included, you can ensure that they use repr ()!

"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
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!"
Copy the code

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! '
Copy the code

(2)! A example of

>>> a = 'some string'
>>> f'{a! r}'
"'some string'"Is equivalent to>>> f'{repr(a)}'
"'some string'"
Copy the code

(3)! An example of d

Similar to the 2

Pycon2019 someone put forward a prospect! Function realization of D:

7. Use of “=” in f-string

Python3.8 has such a feature

a = 5
print(f"{a=}")
Copy the code

The result after printing is zero

a=5
Copy the code

Isn’t it convenient that you don’t have to use f”a={a}” anymore?

8. Use of the walrus operator :=

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

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

The order in which the code runs, first compute a+1 to get a value of 7, and then assign 7 to B, so the code looks like this

b =7
if b>6:
 print(b)
Copy the code

How’s that? Is not a lot easier, but this function can only be used from 3.8.