In this article, we will share with you some different techniques for learning Python. Let’s have fun with Python. I hope these tips can bring convenience to everyone’s work!

Print Print information with color

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 background color -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30, 40 and 41 and 42 red green black 33, 43 and 44 blue yellow 35 to 45 46 green blue purple 36 37 47 Meaning of the white display mode ------------------------- 0 Default Settings of the terminal 1 Highlight 4 Underline 5 Blink 7 Reverse white 8 Invisible 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

1. You can install it using PIP.

pip install schedule
Copy the code

Use cases

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("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)

The timer will run the job function every Monday.

Implement a progress bar

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 inRange (101) : the progress (I) sleep (0.1)Copy the code

Display effect

Oh, my God. Just try it.

In the code above, print has several useful arguments. Sep is used as a separator, and the default is a space. This is set to empty to make each character more compact. Flush = False; flush = False; print to f; When flush = True, it immediately flushs and prints.

The TQDM module was mentioned in the Python download before, which makes it a better 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

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.

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 ()!

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

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:

This functionality was implemented in python3.8, but is no longer used! D is changed to f”{a=}”. Have you seen this video? D should be confused

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?

The walrus operator := is used

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 is not a lot of simple, but this function 3.8 start to use oh.

Here are 8 tips for learning Python. I hope they will help you with your work, and more Python tutorials and tips will continue to be updated.