Most people do not know God's eight operating python

 

 

01 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:

ESC DEF (code = 0): 
return F '\ 033 [{m} code'
Print (ESC ('31;. 1; 0 ') +' Error: '+ ESC () +' Important ')

on the console or Pycharm after running this code you will get results.
Error: important 

of which is red Error underlined, important to the default color, set the format:
\ 033 [display; foreground; m background color 

parameter can be set to the following:

 

 

02 use the 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. pip to install

 

 2. Use Cases

 

 From the literal meaning of the word, you know what to do.

for example:

 

 

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

03 to achieve a progress bar

 

 

Display of results:

Do not FML, and quickly try it soon. Read my article, you do not want to escape @ - @

 

 

 

上面的代码中的 print 有几个有用的参数,sep 的作用是已什么为分隔符,默认是空格,这里设置为空串是为了让每个字符之间更紧凑,end 参数作用是已什么结尾,默认是回车换行符,这里为了实现进度条的效果,同样设置为空串。还有最后一个参数 flush,该参数的作用主要是刷新, 默认 flush = False,不刷新,print 到 f 中的内容先存到内存中;而当 flush = True 时它会立即把内容刷新并输出。

 

04 优雅的打印嵌套类型的数据

 

大家应该都有印象,在打印 json 字符串或者字典的时候,打印出的一坨东西根本就没有一个层次关系,这里主要说的就是输出格式的问题。

 

 

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

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

 

 

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

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

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

 

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

 

 

使用 namedtuple 的缺点很明显了。

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

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

使用示例如下:

 

 

06 f-string 的 !r,!a,!s

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

 

 

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

1. 默认情况下,f-string将使用str(),但如果包含转换标志,则可以确保它们使用repr () !

 

 调用

 

 2. !a的例子

 

 等价于

 

 

3. !d的例子

类似2,pycon2019有人提出的一个展望!d的功能实现:

 

 

在python3.8中已经实现上述功能,不过不再使用!d了改为了f"{a=}"的形式,看过这个视频的发现没有!d应该很懵逼。

07 f-string 里"="的应用

在 Python3.8 里有这样一个功能:

 

 打印之后的结果为

 

 

是不是很方便,不用你再使用f"a={a}"了。

08 海象运算符:=的是使用

 

 

赋值的时候同时可以进行运算,和 Go 语言的赋值类似了。

代码的运行顺序,首先计算 a+1 得到值为 7,然后把 7 赋值给 b,到这里代码相当于下面这样了:

 

 怎么样是不是简单了不少,不过这个功能 3.8 开始才能用哦。

 

 

 

 读者小福利

链接:https://pan.baidu.com/s/1PlqVtLsd7HR_4JmA97MUFA
提取码:n3js

 

 链接容易被举报过期,如果失效了可以在企鹅群 654234959领取

好了,结束了,谢谢大家

 
 

Guess you like

Origin www.cnblogs.com/guran0823/p/12401390.html