[Python杂记1]
1. from...import vs import
2. 元组,列表,字典
T=('a','b')
L=['a','b']
D=
3. 一位数组,二维数组
4. 函数,方法,返回值,参数(默认参数)
def fun():
return 0
5. 和mysql打交道3部曲
def getConnection():
return Connect(host=getDbConf("xx_host"), port=getDbIntConf("xx_port"),
user=getDbConf("xx_user"), passwd=getDbConf("xx_passwd"),
db=getDbConf("xx_db"))
def getCursor(conn):
cur = conn.cursor(cursorclass=cursors.DictCursor)
cur.execute("SET CHARACTER_SET_RESULTS=gbk")
return cur
def executeQuery(sql):
conn = getConnection()
cursor = getCursor(conn)
cursor.execute(sql)
result = cursor.fetchall()
conn.close()
return result
6. 关于中文问题
(1)代码里带中文,需要在程序开头写上
# -*- coding:utf-8 -*-
这样整体的文字都是用utf-8进行编码的
(2)从数据库里读出中文,注意用gbk方式取出,cur.execute("SET CHARACTER_SET_RESULTS=gbk")
但如果此时写入文件的话,由于代码是utf-8编码的,因此要做下编码转化 readFromDBStr.decode('GBK').encode('UTF-8')
1 def transCode(str,codeA,CodeB): 2 3 return str.decode(codeA).encode(codeB)
7. for i in range(X):
xxx
i= 0~X-1
8. split
eg: str="a|b|c"
tArr=[]
tArr = str.split("|")
9. str
10.强制转化
int(a)---比如从数据库里读出字符串,强制转化为整形
str(x)---转为字符串
11. if():...elif():...elif():....else:
12.list
aList = []
aList.append(X)
13.join方法
结合一个list使用,非常有效
",".join(aList)
aList = [] aList.append("a") print ",".join(aList) aList.append("b") print ",".join(aList) --- a a,b

浙公网安备 33010602011771号