Python 常用的代码片段

原文地址

对于Java开发者来说,第一次看见Python的语法可能觉得很奇怪。下面是一些常用的Python代码片段,但是这些代码并不是那么容易被新手开发者记住。这些常用代码片段叫作“具有Python语言特性的代码”。阅读这些编成语言的特性代码可以帮助你更好的学习新编程语言。

这篇文章的目的是列出比较常用的Python语言特性代码, 希望可以给其他开发者提供有用的建议。

# Filter a list

#filter out empty strings in a string 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())

# Query database

db = MySQLdb.connecct("localhost", "username", "password", "dbname")
cursos = "select Column1, Column2 from Table1"
cursor.execute(sql)
results = cursor.fetchall()

for now in results:
    print row[0] + row[1]
db.close()

# Connect 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"

当然, 还有很多Python特性代码没有列出来,我希望你可以以评论的方式添加更多特性代码。

你可能感兴趣的:(Python 常用的代码片段)