Python Basic
Python 速通,参考:https://docs.python.org/zh-cn/3/tutorial/index.html
基础
交互模式
交互模式下,上次输出的表达式会赋给变量 _。把 Python 当作计算器时,用该变量实现下一步计算更简单,例如:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
字符串
字符串可以使用成对的单引号 ('...') 或双引号 ("...") 来标示,结果完全相同,特殊字符如 \n 在单引号('...' )和双引号("..." )里的意义一样。这两种引号唯一的区别是,不需要在单引号里转义双引号 " (但此时必须把单引号转义成 ' ),反之亦然。
如果不希望前置 \ 的字符转义成特殊字符,可以使用 原始字符串,在引号前添加 r
即可:
print(r'C:\some\name')
原始字符串还有一个微妙的限制:一个原始字符串不能以奇数个 \ 字符结束;请参阅 此 FAQ 条目 了解更多信息及绕过的办法。
字符串字面值可以包含多行。 一种实现方式是使用三重引号:"""...""" 或 '''...'''。 字符串中将自动包括行结束符,但也可以在换行的地方添加一个 \ 来避免此情况。 参见以下示例:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
输出如下(请注意开始的换行符没有被包括在内):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
字符串可以用 + 合并(粘到一起),也可以用 * 重复:
>>> 3 * 'un' + 'ium'
'unununium'
相邻的两个或多个 字符串字面值 (引号标注的字符)会自动合并:
>>> 'Py' 'thon'
'Python'
这项功能只能用于两个字面值,不能用于变量或表达式。
字符串支持 索引 (下标访问),第一个字符的索引是 0。单字符没有专用的类型,就是长度为一的字符串;索引还支持负数,用负数索引时,从右边开始计数:
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
注意,-0 和 0 一样,因此,负数索引从 -1 开始。
还可以这样理解切片,索引指向的是字符 之间 ,第一个字符的左侧标为 0,最后一个字符的右侧标为 n ,n 是字符串 长度。例如:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
索引越界会报错,但是,切片会自动处理越界索引。
Python 字符串不能修改,是 immutable 的。因此,为字符串中某个索引位置赋值会报错:
>>> word[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
控制流
if
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
for
# Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
很难正确地在迭代 collection
的同时修改 collection
的内容。更简单的方法是迭代collection
的副本或者创建新的collection
:
# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
range()
>>> list(range(5, 10))
[5, 6, 7, 8, 9]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(-10, -100, -30))
[-10, -40, -70]
有些时候使用 enumerate() 更方便:
>>> 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')]