python的一些零碎的知识点还是挺多的。这里就介绍一些常用的知识点总结。持续更新。
文章目录
1.基础知识
# continue 结束本次循环,继续下一次循环 , break 结束循环
# return结束函数调用,返回‘返回值’,执行return语句,后面的语句不再执行
2. input
a = input() # Input函数获取键盘输入,返回一个输入的字符串
print(type(a))
>>> str
3. 取整
ceil,floor,round
# 向下取整 2.1 > 2
import math
math.floor(2.1) # floor 地板
>>> 2
math.ceil(2.1) # ceil 天花板
>>> 3
print(3 //2) # 默认向下取整
>>> 1
4. 判断数据类型
type,isinstance
type(123) == int #等价isinstance(123,int)
>>> True
# bool是int的子类,type不能判断子类
type(False)==int,isinstance(False,int)
>>> (False, True)
# 使用元祖,从左至右判断,如有遇到符合类型则返回True
isinstance('abc',(int,str,float,bool))
>>> True
5.with
# 方法一,每次打开文件都要执行关闭语句
f = open(r'C:\Users\ASUS PC\Desktop\my.txt','r')
f.read()
f.close()
# 方法二,自动关闭
with open(r'C:\Users\ASUS PC\Desktop\my.txt','w') as f:
f.write('hello')
6. encode和decode
# encode是编码
# encode()可把 str >> bytes
str = 'liu'
test = str.encode()
# decode是解码
# decode()可把 bytes >>str
str = 'liu'
test = str.decode()
7. join
# join()可以连接字符串,元组,列表,并以指定的字符(分隔符)连接,
# 生成一个新的字符串,
## tip:字典只能连接键
#连接字符串
str1 = 'liu','wen','jie'
print('-'.join(str1))
>>> 'liu-wen-jie'
str2 = '+'
print(str2.join(str1))
>>> 'liu+wen+jie'
#连接列表,tip:列表中的元素是str,如果是int报错
list = ['1','2','3','4','5','6','liu']
# ''为直接连接
print(''.join(list))
>>> '123456liu'
# 键需为字符串
dict = {'name':'liu','age':'20'}
print('-'.join(dict))
>>> name-age
8. os
# 创建目录
import os
path = r'C:\Users\ASUS PC\Desktop\img'
dir = os.path.exists(path)
if not dir:
os.mkdir(path)
else:
print('目录已存在')
9. try
# try:
# 可能出异常的代码
# except Exception as result:
# print(result)
# 如果出异常,则执行的代码(不出,不执行)
# else:
# 不出现异常,则执行的代码
# finally:
# 不管出不出异常,一定要执行的代码(如文件的关闭)
# f.close()
# 无异常处理,程序出错直接报错
i = a + 1
>>> NameError: name 'a' is not defined
# -----------------------------------------------------------------
try:
i = a + 1
#异常代码下面的代码不会执行
print(i)
# Exception可以接收所有的异常如NameError,IOErro........
except Exception as result:
print(result)
i = 2 + 1
print(i)
else:
i = 3 + 1
print(i)
>>> name 'a' is not defined
>>> 3
#--------------------------------------------------------------------------
try:
i = 1
except Exception as result:
print(result)
i = 2 + 1
print(i)
else:
i = i + 1
print(i)
>>> 2
10. format
-
传递字符串
"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 >>> 'hello world' "{0} {1}".format("hello", "world") # 设置指定位置 >>> 'hello world' "{1} {0} {1}".format("hello", "world") # 设置指定位置 >>> 'world hello world'
-
传递列表
my_list = ['菜鸟教程', 'www.runoob.com'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的 >>> 网站名:菜鸟教程, 地址 www.runoob.com
-
传递字典
site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site))
-
十进制转化
二进制: '{:b}'.format(11) >>> 1011 十进制: '{:d}'.format(11) >>> 11 八进制: '{:o}'.format(11) >>> 13 十六进制:'{:x}'.format(11) >>> b
-
转义
print ("{} 对应的位置是 {{0}}".format("runoob")) >>> runoob 对应的位置是 {0}
11.设置某段代码运行时间
import time
import eventlet # 导入eventlet这个模块
eventlet.monkey_patch() # 必须加这条代码
with eventlet.Timeout(2, False): # 设置超时时间为2秒
print('这条语句正常执行')
time.sleep(4)
print('没有跳过这条输出')
print('跳过了输出')
>>>:这条语句正常执行
跳过了输出
12.比较日期大小
import datetime
import time
time1 = time.strptime('2018-3-4',"%Y-%m-%d")
time2 = time.strptime('2019-12-1',"%Y-%m-%d")
print(time1)
print(time2)
time2 > time1
# 转化为datetime
time3 = datetime.datetime.strptime('2018-3-4',"%Y-%m-%d")
print(time3)
>>>:
time.struct_time(tm_year=2018, tm_mon=3, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=63, tm_isdst=-1)
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=335, tm_isdst=-1)
True
2018-03-04 00:00:00