声明文件所使用编码
# -*- coding: encoding -*-
# -*- coding: utf-8 -*-
计算乘方使用**,比如5**2表示5的平方
在交互模式下,上一次打印出来的表达式被赋值给变量 _
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
字符串可以用+拼接, 也可以用*重复
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
相邻的两个或多个 字符串字面值 (引号引起来的字符)将会自动连接到一起. 把很长的字符串拆开分别输入的时候尤其有用:
>>> 'Py' 'thon'
'Python'
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
使用过大的索引会产生一个IndexError
错误,但是,切片中的越界索引会被自动处理
>>> word = 'Python'
>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[4:42]
'on'
>>> word[42:]
''
在列表中,给切片赋值也是可以的,这样甚至可以改变列表大小,或者把列表整个清空:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
**print(\*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
将 objects 打印到 file 指定的文本流,以 sep 分隔并在末尾加上 end。 sep, end, file 和 flush 如果存在,它们必须以关键字参数的形式给出. **
enumerate(iterable, start=0)
返回一个枚举对象。iterable 必须是一个序列,或 iterator或其他支持迭代的对象。enumerate()
返回的迭代器的 __next__()
方法返回一个元组,里面包含一个计数值(从 start 开始,默认为 0)和通过迭代 iterable 获得的值。
**
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>>list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>>list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
等价于:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
** sum()
是接受可迭代对象为参数的函数**
>>> sum(range(4)) # 0 + 1 + 2 + 3
6
官方文档看第4.4(
break
和continue
语句,以及循环中的else
子句)
网友评论