本系列文章为《编写高质量代码——改善Python程序的91个建议》的精华汇总。
Pythonic的代码就是具有Python独特风格的代码。通俗说来,就是在保证代码可读性的前提下,尽可能地简洁、优雅,看起来像伪代码一样。
str.format()
格式化字符串,是最Pythonic的字符串格式化方法。# 交换两个变量
a, b = b, a
# for循环遍历容器
for elem in alist:
do_sth_with(elem)
# format格式化字符串
print("{greet} from {language}!".format(greet="hello, world!", language="Python"))
注意要避免的事:
深入理解Pythonic的几个途径:
{}
分隔代码块,Python中用缩进分隔,避免混用空格和Tab键。'
**与**"
**:** 在C语言中,单引号'
表示单个的字符型数据(char),双引号"
表示字符串,默认以\0
结尾;在Python中,'
和"
无明显区别。?:
**: C语言中的三元操作符 C?X:Y
,表示当条件C为True的时候,取值X,否则取值Y。在Python中的等价形式为 X if C else Y
。switch...case
分支语句,Python中可以使用if...elif...else...
代替。Python中有3种形式注释:
需要注意:
x = x + 1 # 这样的注释略近
x = x + 1 # 更好的注释位置
def get_lines(name, lines):
"""Return lines that begin with name.
Lines are expected to look like:
name: space separated values
Args:
name: string, parameter name.
lines: iterable of string, lines in the file.
Returns:
List of values in the lines that match.
"""
retval = []
matches = itertools.ifilter(lambda x: x.startswith(name + ":"), lines)
for line in matches:
retval.extend(line[len(name) + 1 :].split())
return retval
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not ...
def A():
B()
def B():
pass
=
,比较(==, <, >, !=, <=, >=, in, not in, is, is not
),布尔运算(and, or, not
))的左右两边。如x == 1
[]
之间不需要空格,函数的参数=
两侧不需要空格。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。