Python syntax may seem strange at the beginning for Java developers. Wouldn’t it be nice if we first see how Python does the common jobs that we have done using other programming languages, like Java? The common code fragments are call “code idioms”. Reading the code idioms of a programming language is often helpful, and can be served as a shortcut for learning a new programming language.
The intent of this post is to list some of the most commonly used Python code idioms, in the hope that it will provide useful recommendations for other programmers (especially beginners). Remember that in addition to the listings below, there are other frequently used Python code fragments. You may also want to check you the most popular 3000 python modules.
*Note: The order does not reflect each code idiom’s frequency.
# Filter a list
#filter out empty strings in a sting list list = [x for x in list if x.strip()!=''] |
# Read file line by line
with open("/path/to/file") as f: for line in f: print line |
# Write file line by line
f = open("/path/tofile", 'w') for e in aList: f.write(e + "\n") f.close() |
# Regular expression finding
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()) |
# Regular expression search
m = re.search('\d+-\d+', line) #search 123-123 like strings if m: current = m.group(0) |
# Query database
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() |
# Connet a list with a specified separator
theList = ["a","b","c"] joinedString = ",".join(theList) |
# Filter out duplicate elements
targetList = list(set(targetList)) |
# Filter out empty strings from a list of strings
targetList = [v for v in targetList if not v.strip()==''] # or targetList = filter(lambda x: len(x)>0, targetList) |
# Add a list to another list
anotherList.extend(aList) |
# Iterate a dictionary
for k,v in aDict.iteritems(): print k+v |
# Check if any element of a string list appears in a target string
if any(x in targetString for x in aList): print "true" |
Apparently, not all Python code idioms are shown above. I would appreciate if you can add more in your comment.
If you are a Java programmer, and you are totally new to Python, I recommend you read the the following:
When defining regular expression string literals in Python it is more elegant to use “raw strings” where the string literal is prefixed by an ‘r’ and backslashes loose any special processing within the string so you should write in the regular expression example:
... re.search(r'd+-d+', ...
You can use a with statement for the writing too and get an implicit file close:
# Write file line by line
with open("/path/to/file", 'w') as f:
for e in aList:
f.write(e + "n")
It is more pythonic to test an object directly, as empty objects such as empty strings are False leading to:
#filter out empty strings in a sting list
non_empties = [mystring for mystring in input_list if mystring.strip()]
It’s just nice to see the good and neat explanation for each codes. My humble request is i just needed the explanation about the evolution of python programming as i have been working as a research paper writer in buy research paper online website, i have been requested by a client to do the research paper about the evolution and development of python, i am requesting you all to guide me to complete my research paper in a best way.