In this article, we will share some of the different Python techniques and have fun with Python.

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.

def esc(code=0) :return f'[{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 following parameters can be set:

Description: foreground background color -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --30                40black31                41red32                42green33                43yellow34                44blue35                45purple36                46Green, blue37                47Meaning of the white display -------------------------0Terminal Default Settings1The highlighted4Use underscores5flashing7The white shows8Invisible example: [1;31; 40m < ! --1- Highlight31- Foreground color red40- 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

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. schedule.every().monday.do(job)

3. Implement a progress bar

from time import sleep

def progress(percent=0, width=30):
    left = width * percent / / 100
    right = width - left
    print('['.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

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.

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.

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.

from collections importPreviously 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 importPreviously 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.

from dataclasses import dataclass
@dataclass
class Car:
    colorstr
    mileagefloat

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

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

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

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

&gt; &gt; &gt; new_comedian = Comedian("Eric"."Idle"."74") &gt; &gt; &gt; f"{new_comedian}"
'Eric Idle is 74.'&gt; &gt; &gt; f"{new_comedian}"
'Eric Idle is 74.'&gt; &gt; &gt; f"{new_comedian! r}"
'Eric Idle is 74. Surprise! '
Copy the code

(2)! A example of

&gt; &gt; &gt; a ='some string'&gt; &gt; &gt; f'{a! r}'
"'some string'"
Copy the code

Is equivalent to

&gt; &gt; &gt; 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?

The walrus operator := is used

a =6
if (b:=a+1)&gt;6:
   print(b)
Copy the code

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

b =7
if b&gt;6:
   print(b)
Copy the code

How is not a lot of simple, but this function 3.8 start to use oh.

conclusion

That’s the end of today’s content, most of which is a fragment of knowledge recorded in my blog garden. Here I sort out and share with you. My blog park address :www.cnblogs.com/c-x-a/, interested in… Go so it’s going to record some go stuff as well.

Click to become a Registered member of the Community.