Common Python code segments and common Python code segments
Filter list
1 #filter out empty strings in a sting list2 list = [x for x in list if x.strip()!='']
Read files one row at a time
1 with open("/path/to/file") as f:2 for line in f:3 print line
Write files row by row
1 f = open("/path/tofile", 'w')2 for e in aList:3 f.write(e + "\n")f.close()
Regular Expression search
1 sentence = "this is a test, not testing."2 it = re.finditer('\\btest\\b', sentence)3 for match in it:4 print "match position: " + str(match.start()) +"-"+ str(match.end())
Regular match search
1 m = re.search('\d+-\d+', line) #search 123-123 like strings2 if m:3 current = m.group(0)
Query a database
1 db = MySQLdb.connect("localhost","username","password","dbname")2 cursor = db.cursor()3 sql = "select Column1,Column2 from Table1"4 cursor.execute(sql)5 results = cursor.fetchall() 6 for row in results:7 print row[0]+row[1] db.close()
Use specified characters to connect to the list
1 theList = ["a","b","c"]2 joinedString = ",".join(theList)
Remove duplicate elements
1 targetList = list(set(targetList))
Remove null strings from a column of strings
1 targetList = [v for v in targetList if not v.strip()=='']2 # or3 targetList = filter(lambda x: len(x)>0, targetList)
Connect a list to another list
1 anotherList.extend(aList)
Traverse a dictionary
1 for k,v in aDict.iteritems():2 print k+v
Check whether any one of the strings appears in the specified string.
1 if any(x in targetString for x in aList):2 print "true"