……
‘>>>’表示进入python命令,使用’#’进行注释,’…’表示继续输入代码,与上文是一个整体。
数字
1 | # + - * / // % ** |
字符串
可以用单引号或者双引号表示1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
313 * 'un' + 'ium' # 字符串连接用'+',重复用'*'
'unununium'
'Put several strings within parentheses ' # 常量字符串靠在一起时会自动连接 text = (
'to have them joined together.')
text
'Put several strings within parentheses to have them joined together.'
'Python' word =
0] # 字符串可使用索引,没有特定的字符变量,仍是字符串 word[
'P'
-1] # 最后一个字母 word[
'n'
-6] word[
'P'
0:2] # 切片操作,0,1 word[
'Py'
2] + word[2:] # 0,1 2-最后 word[:
'Python'
-2:] word[
'on
>>> word[4:42] # 切片操作超出索引范围
'on'
>>> word[42:]
''
>>> word[2:] = 'py' # 字符串不可变,不能进行赋值操作
...
TypeError: 'str' object does not support item assignment
>>> s = 'supercalifragilisticexpialidocious' # len()得到长度
>>> len(s)
34
使用”””…””” or ‘’’…’’’输出多行字符串。1
2
3
4
5
6
7
8
9print("""\ # ‘\’的目的是让这一行空行不显示
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
列表
可以包含不同的类型,正常使用的还是同一类1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
421, 4, 9, 16, 25] # 创建列表,用逗号隔开,[ , , ] squares = [
squares
[1, 4, 9, 16, 25]
0] # 索引 squares[
1
-3:] # 切片 squares[
[9, 16, 25]
squares[:]
[1, 4, 9, 16, 25]
36, 49, 64, 81, 100] # 连接,必须都是列表 squares + [
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1, 8, 27, 65, 125] cubes = [
3] = 64 # 可变,可以重新赋值 cubes[
cubes
[1, 8, 27, 64, 125]
216) # 使用append()在末尾添加新内容 cubes.append(
7 ** 3) cubes.append(
cubes
[1, 8, 27, 64, 125, 216, 343]
'a', 'b', 'c', 'd', 'e', 'f', 'g'] letters = [
letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
2:5] = [] # 清除某些内容 letters[
letters
['a', 'b', 'f', 'g']
letters[:] = []
letters
[]
'a', 'b', 'c', 'd'] # len()得到长度 letters = [
len(letters)
4
'a', 'b', 'c'] a = [
1, 2, 3] n = [
# 堆叠数组,相当于变成二维 x = [a, n]
x
[['a', 'b', 'c'], [1, 2, 3]]
0] x[
['a', 'b', 'c']
0][1] x[
'b'
注意
1 | 0, 1 a, b = |