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特性代码没有列出来,我希望你可以以评论的方式添加更多特性代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值