python3 小知识点

来源:互联网 发布:mac画网络拓扑图 编辑:程序博客网 时间:2024/06/08 13:29

1.join

拼接字符串

L = []L.append('hello')L.append('world')L.append('hah')print(','.join(L))#打印出  hello,world,hah

2.split()  分割,分割的是字符串,int不行

要分割的字符串.split(分隔符,分割次数),例子:

a = '12121212'print(a.split('2', 2))#打印出  ['1', '1', '1212']

3.rstrip() 删除字符串末尾指定的字符

描述

Python rstrip() 删除 string 字符串末尾的指定字符(默认为空格).

语法

rstrip()方法语法:

str.rstrip([chars])

参数

  • chars -- 指定删除的字符(默认为空格)

返回值

返回删除 string 字符串末尾的指定字符后生成的新字符串。

实例

以下实例展示了rstrip()函数的使用方法:

#!/usr/bin/pythonstr = "     this is string example....wow!!!     ";print str.rstrip();str = "88888888this is string example....wow!!!8888888";print str.rstrip('8');

以上实例输出结果如下:

     this is string example....wow!!!88888888this is string example....wow!!!
str1.strip('str')
#删除字符串首尾的字符,如果是a.strip()是删除字符串首尾的空格a = '1213 2111'print(a.strip('1'))#结果 打印出 213 2




4.全局变量 global
#全局变量的使用,先在函数外面声明局部变量,然后再在函数内部进行声明,表明使用的该变量是全局变量,仅仅在外面声明了全局变量,而没有在函数内部进行声明#那么该全局变量依然无法使用,因为在python中,定义的函数内部声明的变量时该函数的局部变量,即便声明的变量与一个全局变量名字相同,但是如果在函数内部#没有对该变量进行全局声明,那么该变量依然是该函数的一个局部变量,而不会去使用对应的全局变量,例如code2#code1  结果为1global cntcnt = 0def f():    global cnt    cnt += 1f()print(cnt)#code2 结果为1,而不是0global cnt2cnt2 = 0def ff():    cnt2 = 1    print(cnt2)ff()

5.@classmethod 和 @staticmethod
classmthod 是为了让只能实例调用的方法让类也可以直接调用,类的方法中,包含self参数的方法是只有实例才能调用,而直接利用该类型是无法调用的,比如下面的例子

class stu():    def __init__(self):        self.name = 'wulimin'    def f(self):        print('ok')s = stu()s.f() #打印出okstu.f() #报错TypeError: f() missing 1 required positional argument: 'self'


但是使用了@classmethod,这个方法上面代码就可以运行了,@classmethod让类和实例都可以直接调用带self参数的方法

class stu():    def __init__(self):        self.name = 'wulimin'    @classmethod    def f(self):        print('ok')s = stu()s.f() #打印出okstu.f() #打印出ok


@staticmethod 是将类里面的函数变成,可以让类里面的其他方法直接调用该方法,但是如果该方法是该类自带的方法,那么就不需要该装饰器,例如下面的例子

class stu():    def __init__(self):        self.name = 'wulimin'    #@staticmethod    def ff():        print('test')    def f(self):        ff()s = stu()s.f()  # 出现错误,NameError: name 'ff' is not defined

__len__()是dict自带的函数

class stu(dict):    def f(self):        print(len(self))d = stu()d.f()#结果打印出 0,因为没有添加任何东西


加上@staticmethod 后代码如下:

class stu():    def __init__(self):        self.name = 'wulimin'    @staticmethod    def ff():        print('test')    def f(self):        self.ff()s = stu()s.f()  # 打印出 test


这两个装饰器可以混合这用,根据情况自己安排




0 0