空格
Tip
按照标准的排版规范来使用标点两边的空格
括号内不要有空格.
- Yes: spam(ham[1], {eggs: 2}, [])
- No: spam( ham[ 1 ], { eggs: 2 }, [ ] )
不要在逗号, 分号, 冒号前面加空格, 但应该在它们后面加(除了在行尾).
- Yes: if x == 4:
- print x, y
- x, y = y, x
- No: if x == 4 :
- print x , y
- x , y = y , x
参数列表, 索引或切片的左括号前不应加空格.
- Yes: spam(1)
- no: spam (1)
- Yes: dict['key'] = list[index]
- No: dict ['key'] = list [index]
在二元操作符两边都加上一个空格, 比如赋值(=), 比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, or, not). 至于算术操作符两边的空格该如何使用, 需要你自己好好判断. 不过两侧务必要保持一致.
- Yes: x == 1
- No: x<1
当’=’用于指示关键字参数或默认参数值时, 不要在其两侧使用空格.
- Yes: def complex(real, imag=0.0): return magic(r=real, i=imag)
- No: def complex(real, imag = 0.0): return magic(r = real, i = imag)
不要用空格来垂直对齐多行间的标记, 因为这会成为维护的负担(适用于:, #, =等):
- Yes:
- foo = 1000 # comment
- long_name = 2 # comment that should not be aligned
- dictionary = {
- "foo": 1,
- "long_name": 2,
- }
- No:
- foo = 1000 # comment
- long_name = 2 # comment that should not be aligned
- dictionary = {
- "foo" : 1,
- "long_name": 2,
- }