去发现生活中的美好,记录生活中的点点滴滴

python实用技巧汇总

python admin 908℃

1、python md5加密:

str="aa"
md5 = hashlib.md5()
md5.update(str.encode('utf-8'))
sign = md5.hexdigest()

2、python去掉小数点后面多余的0:

print('{:g}'.format(0.2000))
# 0.2

3、判断数据类型:

a = 1
b = [1,2,3,4]
c = (1,2,3,4)
d = {‘a‘:1,‘b‘:2,‘c‘:3}
e = "aaa"
if isinstance(a,int):
    print "a is int"
if isinstance(b,list):
    print "b is list"
if isinstance(c,tuple):
    print "c is tuple"
if isinstance(d,dict):
    print "d is dict"
if isinstance(e,str):
    print "d is str"

4、获取字符串中的数字:

extract_digit = lambda x: re.sub("[^\d\.]", "", x)
s = "这是数字123!"
number = extract_digit(s) #123

5、python中staticmethod方法
staticmethod叫做静态方法,在类里面加上@staticmethod装饰器的方法不需要传入self,同时该方法不能使用类变量和实例变量。在类内部可以调用加上装饰器@staticmethod的方法,同时也不需要实例化类调用该方法
静态方法和类方法的区别在于:
静态方法对类一无所知,只处理参数。
类方法与类一起使用,因为它的参数始终是类本身.

例一:

class Person():
    #加上静态方法
    @staticmethod
    def get_name():
        return 'Jack'
 
    def work(self):
        #调用静态方法
        return f'{self.get_name()} is a teacher'
 
#不需要实例化直接调用get_name()
print(Person.get_name())
 
#实例化调用work()
a_obj = Person()
print(a_obj.work())
 
结果:
Jack
Jack is a teacher

例二:

class Dates:
    def __init__(self, date):
        self.date = date
 
    def getDate(self):
        return self.date
 
    @staticmethod
    def toDashDate(date):
        return date.replace("/", "-")
 
date = Dates("15-12-2016")
dateFromDB = "15/12/2016"
dateWithDash = Dates.toDashDate(dateFromDB)
 
if(date.getDate() == dateWithDash):
    print("Equal")
else:
    print("Unequal")

6、python实现类似mysql order by name , age的排序:

import operator
list1 = [{'name': 'Devin', 'age': 24}, {'name': 'Jane', 'age': 34}]
list1.sort(key=operator.itemgetter('age'))
list1.sort(key=operator.itemgetter('name'))

7、多个列表嵌套循环,可以使用product

list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]
 
for a in list_a:
    for b in list_b:
        for c in list_c:
            if a + b + c == 2077:
                print(a, b, c)
# 70 2000 7

from itertools import product
list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]
 
for a, b, c in product(list_a, list_b, list_c):
    if a + b + c == 2077:
        print(a, b, c)
# 70 2000 7

8、Python 字符串前缀r、u、b、f含义:

1、r/R表示raw string(原始字符串)
在普通字符串中,反斜线是转义符,代表一些特殊的内容,如换行符\n,前缀r表示该字符串是原始字符串,即\不是转义符,只是单纯的一个符号。常用于特殊的字符如换行符、正则表达式、文件路径。

str1 = "Hello\nWorld"
str2 = r"Hello \n World"
print(str1)
print(str2)
# 打印结果如下:
Hello
World
Hello \n World
2、u/U表示unicode string(unicode编码字符串)
前缀u表示该字符串是unicode编码,Python2中用,用在含有中文字符的字符串前,防止因为编码问题,导致中文出现乱码。另外一般要在文件开关标明编码方式采用utf8。Python3中,所有字符串默认都是unicode字符串。

str1 = '\u4f60\u597d\u4e16\u754c'
str2 = u'\u4f60\u597d\u4e16\u754c'
print(str1)
print(str2)
# 打印结果如下:
你好世界
你好世界
3、b/B表示byte string(转换成bytes类型)
常用在如网络编程中,服务器和浏览器只认bytes类型数据。如:send 函数的参数和 recv 函数的返回值都是 bytes 类型。

str1 = 'hello world'
str2 = b'hello world'
print(type(str1))
print(type(str2))
# 打印结果如下:


4、f/F表示format string(格式化字符串)
前缀f用来格式化字符串。可以看出f前缀可以更方便的格式化字符串,比format()方法可读性高且使用方便。


name = "张三"
age = 20
print(f"我叫{name},今年{age}岁。")
# 打印结果如下:
我叫张三,今年30岁。

9、python类继承:

类的继承示例,子类继承父类方法
class  Animal:
    num = 0
    def __init__(self):
        print("父类 Animal")
    def show(self):
        print("父类 Animal 成员方法")

class Cat(Animal):
    def __init__(self):
        print("构建子类 Cat")
    def run(self):
        print("子类 Cat 成员方法")

cat = Cat()
cat.run()   #子类方法
cat.show()  #父类方法

转载请注明:永盟博客 » python实用技巧汇总

喜欢 (5)

Warning: count(): Parameter must be an array or an object that implements Countable in E:\www\blog\wp-includes\class-wp-comment-query.php on line 405