Home >Backend Development >Python Tutorial >Python programming development practical experience and skills released

Python programming development practical experience and skills released

coldplay.xixi
coldplay.xixiforward
2021-03-23 10:45:122964browse

Python programming development practical experience and skills released

Article Directory

  • 1. Decimals should be kept in designated decimal places
    • 1. %f method
    • 2.format function
    • 3.round() function
    • 4.Direct truncation
  • 2. Judgment Data type of variable
    • 1.type():
    • 2.isinstance()
    • 3.__class__.__name__ attribute
  • 3. Class method (@classmethod) in Python
  • 4. str.format and tab character\tSet Chinese alignment
  • 5. Datetime module timedelta Usage of the class
  • 6. Obtain the specific information of the thrown exception
  • 7. Use the BeautifulSoup library to remove the HTML tags in the string

(Free Study recommendation: python video tutorial)

1. Decimals should be retained in designated decimal places

1.%f method

f = 1.23456f1 = '%.4f' % f
f2 = '%.2f' % fprint(f1,type(f1))print(f2,type(f2))

Print

1.2346 <class &#39;str&#39;>1.23 <class &#39;str&#39;>

It is easy to know that this method will round, but convert the floating point type into a string value , is no longer the original value.

2.format function

f = 1.23456f1 = format(f,'.4f')f2 = format(f,'.2f')print(f1,type(f1))print(f2,type(f2))

Print

1.2346 <class &#39;str&#39;>1.23 <class &#39;str&#39;>

Similarly, this method will also round, but the floating point type will be converted into String values ​​are no longer primitive numeric values.

3.round() function

a = 1.23456b = 2.355c = 3.5d = 2.5a1 = round(a, 3)b1 = round(b, 2)c1 = round(c)d1 = round(d)print(a1,type(a1))print(b1,type(b1))print(c1,type(c1))print(d1,type(d1))

Print

1.235 <class &#39;float&#39;>2.35 <class &#39;float&#39;>4 <class &#39;int&#39;>2 <class &#39;int&#39;>

It can be seen that the round() function finally gets a numerical value (floating point type or integer type), but the rules of "rounding" and "rounding" are not necessarily true:
(1) In the round(x,n) function, whether to carry or round depends on n digits and n 1 decimal digits Value
(2) It is easy to be confused only when the n 1-digit number is 5. If n is an even number, then the n 1-digit number is 5, then carry, for example, round (1.23456, 3) finally becomes 1.235
(3) If n is an odd number, then n 1 bit is the number 5, and there is no carry, such as round (2.355, 2), the final value is 2.35
(4) If n is 0, that is, when n is not filled in, The final result is the opposite of the above, that is, when the integer part is an even number, the decimal place 5 is not carried, for example (round (2.5) becomes 2).
(5) When the integer part is an odd number, the decimal place is rounded up to 5. (round (3.5) becomes 4)

4. Directly truncate

a = int(1.23456 * 1000) / 1000print(a)

and print 1.234
This method is simple, crude and direct Remove the following ones, regardless of whether they are greater than 5.

2. Determine the data type of the variable

1.type():

a = 1.23print(type(a))

Print< class 'float'>.

2.isinstance()

The prototype is isinstance(x, A_tuple),

a = 1.23tp = isinstance(a,float)print(tp)

PrintTrue .

3.class.__name__ attribute

Use the __class__.__name__ attribute of the variable, which is also type() The essence of the method:

num = 1.23print(num.__class__.__name__)

Print:

float

3. Class method (@classmethod) in Python

When doing object-oriented programming in Python , it is often necessary to use the classmethod class method, which is not a method in the class.
Class methods are also a practical technique, which can be described simply as: "Class methods make class templates memorable."
Class template is the class we define. Under normal circumstances, if you do not use class methods to instantiate a class, the class itself has no memory. Just when a static template is applied multiple times. If we want the class to record some memory after each instantiation, it will be useful for many operations.

class Man:
    id = 0 # 类变量
    def __init__(self, name):
        self.name = name
        self.id = self.id_number()
 
    @classmethod
    def id_number(cls):
        cls.id += 1
        return cls.id
 a = Man('A')print(a.id)b = Man('B')print(b.id)

Print

12

Instantiate the Man class twice, and the id of each instance is different. This is achieved by relying on class methods: first, use @classmethod to describe the class method, and then use "cls" to represent this class. The processing of class attributes by class methods is memorized.

It should be noted that the variables processed by the class method must be class variables. Because you can't use self to address instance variables in class methods, you need to put the class variables at the front of the description, as shown in "id=0" above. Class variables can be accessed by self, so after the class variables are defined, there is no need to describe the class variables again in the _init_ function. Therefore, self.id is not necessarily needed in the above code.

4. str.format and tab character \tSet Chinese alignment

str.format formats the string, {:<x }The syntax of means left alignment, {:>x} means right alignment, {:^x} means centering), and less than x digits will be automatically filled in (default Fill in spaces), but it does not support Chinese characters very well, so it will lead to the phenomenon of non-alignment when there are multiple lines of Chinese strings. You need to consider the length of the string and encode the Chinese string before calculate.

#name是包含中文的字符串,22是整个字符串一行的总长度,一般要顾及测试才能得到,\t后的x是一标记字符,可换为别的所需的字符串print('[{string:<{len}}\tx&#39;.format(string=string+&#39;]&#39;,len=22-len(string.encode(&#39;GBK&#39;))+len(string)))

For details, please refer to https://blog.csdn.net/excaliburrr/article/details/76794451

5. Use of timedelta class in datetime module

timedelta对象表示两个不同时间之间的差值, 这个差值的单位可以是:天、秒、微秒、毫秒、分钟、小时、周。
如果使用time模块对时间进行算术运算,只能将字符串格式的时间和struct_time格式的时间对象先转换为时间戳格式,然后对该时间戳加上或减去n秒,最后再转换回struct_time格式或字符串格式,这显然很不方便。而datetime模块提供的timedelta类可以让我们很方面的对datetime.date, datetime.timedatetime.datetime对象做算术运算,且两个时间之间的差值单位也更加容易控制。
datetime.timedelta类的定义:

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, hours=0, weeks=0)

所有参数都是默认参数,因此都是可选参数。参数的值可以是整数或浮点数,也可以是正数或负数。内部值存储days、seconds 和 microseconds,其他所有参数都将被转换成这3个单位:

  • 1毫秒转换为1000微秒
  • 1分钟转换为60秒
  • 1小时转换为3600秒
  • 1周转换为7天

然后对这3个值进行标准化,使得它们的表示是唯一的:

  • microseconds : [0, 999999]
  • seconds : [0, 86399]
  • days : [-999999999, 999999999]

类属性

类属性名称描述
timedelta.mintimedelta(-999999999)
timedelta.maxtimedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)
timedelta.resolutiontimedelta(microseconds=1)

实例方法和属性

实例方法/属性名称描述
td.days天 [-999999999, 999999999]
td.seconds秒 [0, 86399]
td.microseconds微秒 [0, 999999]
td.total_seconds()时间差中包含的总秒数,等价于: td / timedelta(seconds=1)
方法/属性描述
datetime.datetime.now()返回当前本地时间(datetime.datetime对象实例)
datetime.datetime.fromtimestamp(timestamp)返回指定时间戳对应的时间(datetime.datetime对象实例)
datetime.timedelta()返回一个时间间隔对象,可以直接与datetime.datetime对象做加减操作
>>> import datetime>>>>>> datetime.timedelta(365).total_seconds() # 一年包含的总秒数31536000.0>>> dt = datetime.datetime.now()>>> dt + datetime.timedelta(3) # 3天后datetime.datetime(2020, 1, 22, 11, 17, 0, 214877)>>> dt + datetime.timedelta(-3) # 3天前datetime.datetime(2020, 1, 16, 11, 17, 0, 214877)>>> dt + datetime.timedelta(hours=3) # 3小时后datetime.datetime(2020, 1, 19, 14, 17, 0, 214877)>>> dt + datetime.timedelta(hours=-3) # 3小时前datetime.datetime(2020, 1, 19, 8, 17, 0, 214877)>>> dt + datetime.timedelta(hours=3, seconds=30) # 3小时30秒后 datetime.datetime(2020, 1, 19, 14, 17, 30, 214877)

更多关于Python对日期、时间的处理可参考https://www.jb51.net/article/105840.htm。

六、获取抛出的异常具体信息

很多时候,在Python运行抛出异常并接收到之后需要显示异常的具体信息,包括异常内容、异常所在的行数和异常所在的Python文件等等,分别使用args[0]__traceback__.tb_lineno__traceback__.tb_frame.f_globals["__file__"]属性即可,示意如下:

def get_exception_info():
    try:
        s = 2 / 0
    except Exception as e:
        print('异常内容:', e.args[0])
        print('异常行数:', e.__traceback__.tb_lineno)
        print('异常文件:', e.__traceback__.tb_frame.f_globals["__file__"])get_exception_info()

打印:

异常内容: pision by zero
异常行数: 8异常文件: XXX/test.py

七、使用BeautifulSoup库去掉字符串中的HTML标签

有时候,字符串中含有HTML标签,如

text = """<p>
<h1>Title</h1>
<p>A long text........ </p>
<a href=""> a link </a>
</p>"""

需要得到'\nTitle\nA long text........ \n a link \n',可以使用正则表达式匹配,但是稍嫌麻烦,此时可以直接使用BeautifulSoup库进行转化,更加简单,如下:

from bs4 import BeautifulSoup

text = """<p>
<h1>Title</h1>
<p>A long text........ </p>
<a href=""> a link </a>
</p>"""clean_text = BeautifulSoup(text, "lxml").textprint(clean_text)

打印:

Title
A long text........ 
 a link

显然,此时已经去掉了字符串中的HTML标签。

相关免费学习推荐:python教程(视频)

The above is the detailed content of Python programming development practical experience and skills released. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete