python3 笔记

1、指定编码方式

# import importlib,sys
# importlib.reload(sys)

参考: https://www.zhihu.com/question/31110175

后记:

发现上面那个不行,就用下面这个

from urllib.parse import quote

quote("* and _xxxx_name_:1111 and 哈哈哈哈 | with_pack_meta", 'utf-8')

 

2、字符格式转换

 

3、判断字符是否为纯数字

q="12ee3"
print (q.isdigit())

 

4、引用文件库小技巧

比如要导入 we文件下rr文件中han文件(库),可以像下面这样写

from we.rr import han

5、文件夹下的__init__.py 初始化文件(告诉python 这个是个可以调用的库,引入里面函数的方法如下)

 

6、去掉前后空格的函数 strip()

a=" 12 3 "
print (a.strip())

 

7、判断变量是否赋值成功 (这个还没试过)

if aa == None:

  print "赋值失败" 

下面这个可以

if aa:

  print “不为空”

else:

  print “为空”

 

8、try 和 except 用法的解释

try:
  1/0
except Exception as ex:
  print ex
  print "自己要输出的东西"

这里 except 就和with类似,ex是上文返回的东西

可以参考: https://www.cnblogs.com/kaibindirver/p/12688998.html

https://www.runoob.com/python/python-exceptions.html  还可以定义其他判断出错的方法

 

9、函数指定参数传输

def AS(a=None,b=3):

  print a,b

可以指定传b参数   AS(b=5)

 

10、Python continue 语句跳出本次循环,而break跳出整个循环

 

11、getattr()函数 和 setattr() 函数

getattr()函数   #获取类里面某个值

getattr(a, 'bar',"不存在")    获取a类里面bar值不存在,就返回"不存在",不加这个 类里面不存在这个值代码会报错

参考:https://www.runoob.com/python/python-func-setattr.html

setattr() 函数 #设置类里面某个值

setattr(a, 'bar',"设置的值")

参考: https://www.runoob.com/python/python-func-getattr.html

 

类里面写的提示的方法

 

12、循环往数组里面添加字符的高级写法(列表推导式)

 

13、当字典取值为空,想默认赋值的高级语法:

def __cut_book_data(cls,data):
  book={
    'author':'、'.join(data["author"]),
    'summary':data["summary"] or '',
    'image':data["image"]
    }
return book

 

14、print换行的方法

print(1,end='')

 

15、输出中文乱码问题

import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

https://www.cnblogs.com/llfctt/p/11833383.html

 

16、取字典键的值为空,返回一个默认值

a={}

a.get("aaa",0)

 

17、格式化新写法

format   format 格式化函数

a = 1 
b = 2 
c = 3 
print(f'a={a}, b={b}, c={c}') 
# 等价于print('a={}, b={}, c={}'.format(a, b, c))

 

18、三元表达式

三元表达式

 

19、合并2个字典的方法

dnew = dict(d1, **d2)

 

20、查看变量的类型是否为指定类型

a=123
if isinstance(a, int):
	print("相同")
    
和下面的逻辑一样

if a ==type(123)


#判断变量类型的函数
def typeof(variate):
    type=None
    if isinstance(variate,int):
       type = "int"
    elif isinstance(variate,str):
      type = "str"
   elif isinstance(variate,float):
     type = "float"
   elif isinstance(variate,list):
       type = "list"
   elif isinstance(variate,tuple):
       type = "tuple"
   elif isinstance(variate,dict):
       type = "dict"
   elif isinstance(variate,set):
       type = "set"
    return type

 

21、推导式写法 去除列表中为空的元素

lst = ["apple", "", "banana", "", "orange"]

lst = [element for element in lst if element != ""]

print(lst)

```

输出结果为:

```

["apple", "banana", "orange"]

 

22、小数点转百分比

http://www.enlanhao.com/code/289271.html
num = 0.22
percent = '%.2f%%' % (num*100)
print(percent)

 

33、保留小数点后2位

percentage=1.0111
"%.2f"%percentage

 

33、数组里面的值直接赋值出去

 

34、获取数组内的元素 和 他的下标用enumerate函数

for i, item in enumerate(all_data):
    

 

posted @ 2020-03-26 21:08  凯宾斯基  阅读(243)  评论(0编辑  收藏  举报