windows 安装python
尽量下载32位的python2
字符串拼接
data = "http://users.seeyouyima.com/v2/" + "login"
出现 SyntaxError: Non-ASCII character '\xe7' in file
问题
在文件最顶部加上
#-*- coding: UTF-8 -*-
urllib2 设置header
将json中的unicode 转成utf8中文
像 \u54c8\u54c8
转成哈哈
import json
js = json.loads('{"haha": "哈哈"}')
print js #输出 {"haha": "\u54c8\u54c8"}
print json.dumps(js) #输出{"haha": "哈哈"}
requests
字典转json
判断变量类型
if type(var) == list:
print 'list'
变量类型转换
# int 转 string
str = str(int_val)
# string 转 int
int_val = int(str_val)
报错 TypeError: string indices must be integers
找到不该字典的key
unicode 转 str
_msg = send_res['message'].encode('utf-8')
查看当前工作目录
retval = os.getcwd()
print "当前工作目录为 %s" % retval
修改当前工作目录
os.chdir( path )
获取当前时间戳
import time
res = int(time.time())
print res
正则匹配多行
re.S:.将会匹配换行符,默认.逗号不会匹配换行符
re.findall(r"a(\d+)b.+a(\d+)b","a23b\na34b",re.S)
字符串转时间,时间增加多少分钟
from datetime import datetime as dt
import datetime
def str2datetime():
datetime_object = dt.strptime('2016-12-08 12:05:02', '%Y-%m-%d %H:%M:%S')
print datetime_object
print type(datetime_object)
def timedelta():
datetime_object = dt.strptime('2016-12-08 12:05:02', '%Y-%m-%d %H:%M:%S')
print datetime_object + datetime.timedelta(minutes=-5)
抓取gb2312页面时乱码解决方法
res = str.decode('gb18030','ignore').encode('utf-8')
返回的内容被gzip后的解压方法
str = '被压缩过的内容'
compressedstream = StringIO.StringIO(str)
gzipper = gzip.GzipFile(fileobj=compressedstream)
data = gzipper.read() # data就是解压后的数据
时间戳转标准时间格式
datetime.datetime.fromtimestamp(time_now)
时间戳获取年月日时分秒
import datetime
now = datetime.datetime.now()
print now.year, now.month, now.day, now.hour, now.minute, now.second
# 2015 5 6 8 53 40
datetime获取今年第几个星期
week = datetime.datetime.isocalendar()[1]
print week
md5加密
import hashlib
m2 = hashlib.md5()
m2.update(src)
print m2.hexdigest()
字符串转unicode
'abc'.decode('utf-8') # str to unicode
> u'abc'
u'abc'.encode('utf-8') # unicode to str
>'abc'
json不转义中文
json.dumps({'text':"中文"},ensure_ascii=False,indent=2)
获取命令行输入的参数
import sys
#除了文件名以外的参数
sys.argv[1:]
# python example.py one two three
print sys.argv
# ['example.py', 'one', 'two', 'three']