1. “”“%s"""的用法
#"""%s"""是不不会改格式,且以字符串原来的格式输出结果是:{'kk': 123} <type 'dict'>a={'kk':123} print a,type(a) print """%s"""%a,type("""%s"""%a)
{'kk': 123} <type 'str'>
2. not的应用
# #有列表值,和空列表,查看not的结果,空列表的值是为假
result=['aa','bb'] result1=[] print not result print not result1
结果:False True
3.set集合是去除重复
#set集合去重 a=[1,2,3,4,1,2] k=set(a) print k print type(k)结果:set([1, 2, 3, 4])
<type 'set'>
4.python中没有Null,只有None,如果jason中有aa:null,则要改成None
5.二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value:这样可以代替if else语句。只有json即字典才有get方法
d={'a':1,'b':2}
d.get('accessToken','super_token')
6.enumerate集合返回索引及值
a={'1':1,'2':2,'3':3} for index,sel in enumerate(a): print index,sel返回结果如下:0 1 1 3 2 2
但改成index+1,可以指定索引的起始值print index+1,sel返回值如下:1 1 2 3 3 27.strip():删除两边的空格用print可以将中文打印出来,unicode是带中文的汉字print u'XXXXX'
8. 字符串传参str格式:“{}:{}”这两个传参数
print "{}:{}".format(123,123)
print "%s:%s"%(123,123) # a = base64.b64encode("{}:{}".format(123, 123)) # print a
9.标志位flag:
常用于search(config, flag=True):
if flag:
body = body_value
else:
body=body_time
调用函数:search(config_178,flag=0)或者search(config_178,0)
eg:(1)flag为0时,即为false;flag=1时为True
eg: if 0:print "aaa" ==>未打印(2)"",[],{}都为falseeg:if []:print "aaa" ==>未打印eg:scrapy中的要从index=1开始取数据时,则用到if index,因为index=0是为False不会执行,当index=1时才会执行if后面的语句
for index, a in enumerate(response.xpath('//*[@id="main"]/div[2]/div[2]/div[1]/ul/div')):print index #相当于标志位,index=0时为False不执行,因为第一个不是课程,故从index=1开始。所以if index: if index:10. for 循环的两种取值:
a=[1,2,3,4,5]
for i in a: #此处取的是a中的元素
print i
#结果是:1,2,3,4
for i in range(len(a)): #此处i是0,1,2,3,是下标
print a[i]
#要取到各自下标才会取到元素
11.带任意数量参数的函数 def function(arg1="",arg2=""): print "arg1:{0}".format(arg1) print "arg2:{0}".format(arg2) function("Hello","Word") function() def foo(*args): numargs=len(args) print "Number of arguments:{0}".format(numargs) for i,x in enumerate(args): print "Argument {0} is:{1}".format(i,x) foo() foo("hello") foo("hello","World","Again") 12.使用Glob()查找文件 import glob files=glob.glob('*.py') print files #使用Glob()查找文件 #它像是一个更强大版本的listdir()函数 import glob #get all py files files=glob.glob('*.py') print files 13.可以像下面这样查找多个文件类型 import itertools as it,glob,os def multiple_file_types(*patterns): return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns) for filename in multiple_file_types("*.txt","*.py"): print filename #如果你想得到每个文件的绝对路径,可以在返回值上调用realpath()函数 def multiple_file_types(*patterns): return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns) for filename in multiple_file_types('*.txt','*.py'): realpath=os.path.realpath(filename) print realpath 14.#inspect模块,检测语法 import logging,inspect logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(filename)s:%(lineno)-4d:%(message)s', datefmt='%m-%d %H:%M',) logging.debug('A debug message') logging.info('Some information') logging.warning('A shot across the bow') def test(): frame,filename,line_number,function_name,lines,index=\ inspect.getouterframes(inspect.currentframe())[1] print (frame,filename,line_number,function_name,lines,index) test()
15.生成一个唯一的密码,md5码或者hash加密。hash加密比md5码更安全 #生成唯一ID #其实有一个名为uuid()的python函数是用于这个目的的。 import uuid result=uuid.uuid1() print result #为了减少重复情况,可以使用下面两个函数 import hmac,hashlib key='1' data='a' print hmac.new(key,data,hashlib.sha256).hexdigest() m=hashlib.sha1() m.update("The quick brown fox jumps over the lazy dog") print m.hexdigest()
加盐后摘要:
由于同一个消息通过摘要算法得到的摘要是相同的,因此可以通过撞库的方式得到原始消息值。解决方式是,添加一个salt拼接原始消息后再进行计算。
import hashlib #####md5##### hash=hashlib.md5('8980aFs09f') hash.update('admin') print hash.hexdigest() #以上等价与 hash=hashlib.md5() hash.update('8980aFs09fadmin') print hash.hexdigest()15.序列化import picklevariable=['hello',42,[1,'two'],'apple']#序列化内容file=open('serial.txt','w')serialized_obj=pickle.dumps(variable)file.write(serialized_obj)file.close()#反序列化target=open('serial.txt','r')myObj=pickle.load(target)print serialized_objprint myObj16.JSONimport jsonvariable=['hello',42,[1,'two'],'apple']print "Original{0}-{1}".format(variable,type(variable))#encodingencode=json.dumps(variable)print "Encoded{0}-{1}".format(encode,type(encode))#decodingdecoded=json.loads(encode)print "Decoded{0}-{1}".format(decoded,type(decoded))#压缩字符import zlibstring=""" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut elit id mi ultricies adipiscing. Nulla facilisi. Praesent pulvinar, sapien vel feugiat vestibulum, nulla dui pretium orci, non ultricies elit lacus quis ante. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam pretium ullamcorper urna quis iaculis. Etiam ac massa sed turpis tempor luctus. Curabitur sed nibh eu elit mollis congue. Praesent ipsum diam, consectetur vitae ornare a, aliquam a nunc. In id magna pellentesque tellus posuere adipiscing. Sed non mi metus, at lacinia augue. Sed magna nisi, ornare in mollis in, mollis sed nunc. Etiam at justo in leo congue mollis. Nullam in neque eget metus hendrerit scelerisque eu non enim. Ut malesuada lacus eu nulla bibendum id euismod urna sodales. """print "Original Size:{0}".format(len(string))compressed=zlib.compress(string)print "Compressed Size:{0}".format(len(compressed))decompressed=zlib.decompress(compressed)print "Decompressed Size:{0}".format(len(decompressed))17.注册shutdown函数#有可模块叫atexit,它可以让你在脚本运行完后立马执行一些代码import atexitimport timeimport mathdef microtime(get_as_float=False): if get_as_float: return time.time() else: return '%f %d' % math.modf(time.time())start_time=microtime(False)atexit.register(start_time)def shutdown(): global start_time print "Execution took:{0} seconds".format(start_time)atexit.register(shutdown)
16. python3 中可用自带迭代器的内置函数
# 全排列combinations方法重点在组合和permutations函数重点在排列
from itertools import permutations,combinationsa=list(combinations('123',2))print(a) ===>结果是:[('1', '2'), ('1', '3'), ('2', '3')]b=list(permutations('123',2))print(b) ===》结果是:[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]
17.时间格式strftime
import time #time.time是时间戳格式 print(time.time()) ===》结果是:1499068942.69556 #strftime是格式化时间 print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))) ==>结果是:2017-07-03 16:02:2218.列表转换为字典#time和datetime区别 #time是float为基础,小数点后是毫秒,整数部分是秒 #datetime是int,略去了毫秒部分。datetime是time的升级版,对time进行了封装 #time相关的方法: # time.time,==》返回的是时间戳timestamp # time.localtime(timestamp) ==>time.localtime(time.time()) ==>返回的是time.struct_time import datetime print(time.localtime(time.time())) time.sleep(1) #将返回值中转换成字符串形式 print(time.ctime()) #==>Mon Jul 3 16:36:25 2017 #也是将gmtime()或localtime()返回的时间的元组和struct_time转换为以下字符串形式 print(time.asctime()) #==》Mon Jul 3 16:40:55 2017 print(time.gmtime()) #==>返回的是struct_time的值,和上面的localtime返回结果一致 #格式化strftime print(time.strftime("%Y-%m-%d %H-%M-%S",time.localtime(time.time()))) #datetime的用法,它对time进行了封装,提供了更多实用的函数。在datetime模块中包含了几个类,具体关系如下: #1.timedelta 主要用于计算时间跨度 #2.tzinfo 时区相关 #3. time 只关注时间 #4. date 只关注日期 #5. datetime #同时有时间和日期 #用得比较多的是datetime.datetime和datetime.timedelta # datetime.year # datetime.month # datetime.day # datetime.hour # datetime.hour # datetime.minute # datetime.second # datetime.microsecond # datetime.tzinfo print(datetime.datetime.now()) #返回当前时间,相当于time中的localtime ==>返回结果:2017-07-04 09:03:30.344590 print(datetime.datetime.today()) #返回当前时间,相当于time中的localtime ==》返回结果:2017-07-04 09:03:30.344665 print(datetime.datetime.year) #返回year对象 ==》返回结果:<attribute 'year' of 'datetime.date' objects> print(datetime.datetime.time) #返回time对象 print(datetime.datetime.date) #返回date对象 TIME=datetime.datetime.now() print(TIME.year) #返回年 ==>返回结果: 2017 #下面的isocalendar是datetime.datetime的方法 print(datetime.datetime.isocalendar(TIME)) #返回2017年第27周星期一 print(TIME.isoweekday()) #返回星期几:1表示星期一 print(TIME.strftime("%Y.%m.%d %H-%M-%S")) #按格式输出 ==》返回结果:2017.07.04 09-03-30
#将两个列表转换成字典用dict
eg:
l=[1,2] i=['a','b'] print(dict([i,l]))
19.filter内置函数,过滤
filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
eg:过滤掉偶数
def is_odd(x):
return x % 2==1
p=filter(is_odd,[1,4,6,7,9,12,13,17])
#过滤掉偶数,结果
[1,7,9,13,17]
20.zip内置函数:
使用zip()函数来可以把列表合并,并创建一个元组对的列表。在python
3.0
中
zip
()是可迭代对象,使用时必须将其包含在一个
list
中,方便一次性显示出所有结果.
eg:
a=[1,2,3]
b=[4,5,6]
z=list(zip(a,b))
print z
#返回值:[(1, 4), (2, 5), (3, 6)]
zip()参数可以接受任何类型的序列,同时也可以有两个以上的参数;当传入参数的长度不同时,zip能自动以最短序列长度为准进行截取,获得元组。
eg:
str1='abc'
str2='def123'
z=list(zip(str1,str2))
print z
#返回值如下:[('a', 'd'), ('b', 'e'), ('c', 'f')]
zip()方法用在for循环中,就会支持并行迭代:指的是x,y都同时循环取下一个
a2=[4,5,6]
for (x,y) in zip(a1,a2):
print x,y,'--',x*y
3 5 -- 15
4 6 -- 24