python stunning skills you have mastered a few?

This article and share some Python different skills, experience Python bring you the fun of it.

python these amazing skills, you can get a few?

 

1.print colored print information

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

But you know what, the Print to print out the font color can be set.

A small example

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

After the console or Pycharm run this code you will get results.

Error:important

Where Error is underlined in red, important as the default color

Format is provided: [display; foreground; background color m

The following parameters can be set:

Description: 
foreground color background color
---------------------------------------
30 40 Black
31 41 red
32 42 green
3343 yellow
3444 blue
3545 purple
3646 cyan
3747 white
display sense
----------------------- -
terminal turns default setting
a highlight
4 with an underscore
5 scintillator
7 highlight
8 invisible
example:
[1; 31 is; 40m <- l- 31- foreground red highlight background color black 40 -! ->

2. Use a timer in Python

Today saw a more humane timing module schedule, the current number of star to 6432, is still very popular, this module also adhering to this principle For Humans, it is recommended to everyone here. Address https://github.com/dbader/schedule

1 can be installed through the pip.

pip install schedule

2. 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("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 to do.

for example:

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

This code is the role that the word meant, a timer function will run every Monday job, how kind is not very simple.

3. To achieve a progress bar

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

Display of results

python these amazing skills, you can get a few?

 

The above code print There are several useful parameters, what has been the role of sep is a delimiter, the default is blank, an empty string is set here in order to allow between each character more compact, end parameters of what the role is ending the default is the carriage return character, in order to achieve the effect where the progress bar, the same is set to the empty string. There is one final argument flush, the main effect of this parameter is refreshed, the default flush = False, not refresh, print the contents of the pre-existence of f into memory; and it will immediately refresh the content and output when flush = True when.

4. elegant nested type print data

We should have the impression, at the time of printing json string or dictionary, print out the lump of stuff is simply not a hierarchical relationship, where the main problem is the output of said format.

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

大家可以自己试试只用 print 打印 my_mapping,和例子的这种打印方法。

如果我们打印字典组成的列表呢,这个时候使用 json 的 dumps 方法肯定不行的,不过没关系,用标准库的 pprint 方法同样可以实现上面的方法。

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

5.功能简单的类使用 namedtuple 和 dataclass 的方式定义

有时候我们想实现一个类似类的功能,但是没有那么复杂的方法需要操作的时候,这个时候就可以考虑下下面两种方法了。

第一个,namedtuple 又称具名元组,带有名字的元组。它作为 Python 标准库 collections 里的一个模块,可以实现一个类似类的一个功能。

from collections import namedtuple
# 以前简单的类可以使用 namedtuple 实现。
Car = namedtuple('Car', 'color mileage')
my_car = Car('red', 3812.4)
print(my_car.color)
print(my_car)

但是呢,所有属性需要提前定义好才能使用,比如想使用my_car.name,你就得把代码改成下面的样子。

from collections import namedtuple
# 以前简单的类可以使用 namedtuple 实现。
Car = namedtuple('Car', 'color mileage name')
my_car = Car('red', 3812.4,"Auto")
print(my_car.color)
print(my_car.name)

使用 namedtuple 的缺点很明显了。

所以现在更优的方案,那就是 Python3.7 加入到标准库的 dataclass。

其实在 3.6 也可以使用不过需要它被作为第三方的库使用了,使用 pip 安装即可。使用示例如下:

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出现在Python3.6,作为当前最佳的拼接字符串的形式,看下 f-string 的结构

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

其中'!s' 在表达式上调用str(),'!r' 调用表达式上的repr(),'!a' 调用表达式上的ascii()

(1.默认情况下,f-string将使用str(),但如果包含转换标志,则可以确保它们使用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!"

调用

>>> 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.!a的例子

>>> a = 'some string'
>>> f'{a!r}'
"'some string'"

Equivalent to

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

(3! D of example

Similar 2

pycon2019 was presented a vision d function to achieve!:

python these amazing skills, you can get a few?

 

In python3.8 above functions have been implemented, but no longer used! D to form a f "{a =}" found not seen the video! D should be ignorant force in 7.f-string "= "Applications

There is such a feature in Python3.8

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

After the results are printed as

a=5

Is not very convenient, do not you then use f "a = {a}" a.

8. walrus operator: = is used

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

When the assignment operation can be carried out simultaneously, and similar to the assignment in Go.

Run the code sequence, first a + 1 is calculated to obtain a value of 7, and then assigned to B 7, so the code here corresponds to the following

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

How kind is not simply a lot?

Guess you like

Origin www.cnblogs.com/xuegod/p/11413702.html
Recommended