這些常用的代碼段可以讓不懂Python的人感受到Python的魅力, 同時讓編寫啰里啰嗦語言的人們看到未來~~ 更快地了解Python, 加入Python部落(www.freelycode.com)
過濾列表
#filter out empty strings in a sting list list = [x for x in list if x.strip()!='']
一行一行地讀文件
with open('/path/to/file') as f: for line in f: print line
逐行寫文件
f = open('/path/tofile', 'w') for e in aList: f.write(e + '\n')f.close()
正則匹配查找
sentence = 'this is a test, not testing.' it = re.finditer('\\btest\\b', sentence) for match in it: print 'match position: ' + str(match.start()) +'-'+ str(match.end())
正則匹配搜索
m = re.search('\d+-\d+', line) #search 123-123 like strings if m: current = m.group(0)
查詢數(shù)據(jù)庫
db = MySQLdb.connect('localhost','username','password','dbname') cursor = db.cursor() sql = 'select Column1,Column2 from Table1' cursor.execute(sql) results = cursor.fetchall() for row in results: print row[0]+row[1] db.close()
用指定字符連接列表
theList = ['a','b','c'] joinedString = ','.join(theList)
去除重復(fù)元素
targetList = list(set(targetList))
在一列字符串中去除空字符串
targetList = [v for v in targetList if not v.strip()==''] # or targetList = filter(lambda x: len(x)>0, targetList)
將一個列表連接到另一個列表后面
anotherList.extend(aList)
遍歷一個字典
for k,v in aDict.iteritems(): print k+v
檢查一列字符串中是否有任何一個出現(xiàn)在指定字符串里
if any(x in targetString for x in aList): print 'true'
|