……
‘>>>’表示进入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'
text = ('Put several strings within parentheses ' # 常量字符串靠在一起时会自动连接
'to have them joined together.')
text
'Put several strings within parentheses to have them joined together.'
word = 'Python'
word[0] # 字符串可使用索引,没有特定的字符变量,仍是字符串
'P'
word[-1] # 最后一个字母
'n'
word[-6]
'P'
word[0:2] # 切片操作,0,1
'Py'
word[:2] + word[2:] # 0,1 2-最后
'Python'
word[-2:]
'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
42squares = [1, 4, 9, 16, 25] # 创建列表,用逗号隔开,[ , , ]
squares
[1, 4, 9, 16, 25]
squares[0] # 索引
1
squares[-3:] # 切片
[9, 16, 25]
squares[:]
[1, 4, 9, 16, 25]
squares + [36, 49, 64, 81, 100] # 连接,必须都是列表
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
cubes = [1, 8, 27, 65, 125]
cubes[3] = 64 # 可变,可以重新赋值
cubes
[1, 8, 27, 64, 125]
cubes.append(216) # 使用append()在末尾添加新内容
cubes.append(7 ** 3)
cubes
[1, 8, 27, 64, 125, 216, 343]
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2:5] = [] # 清除某些内容
letters
['a', 'b', 'f', 'g']
letters[:] = []
letters
[]
letters = ['a', 'b', 'c', 'd'] # len()得到长度
len(letters)
4
a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n] # 堆叠数组,相当于变成二维
x
[['a', 'b', 'c'], [1, 2, 3]]
x[0]
['a', 'b', 'c']
x[0][1]
'b'
注意
1 | a, b = 0, 1 |