Numbers
>>> 18/4 #/除返回的总是浮点数
4.5
>>> 5/5
1.0
>>> 18//4 #地板除,返回的是整数
4
>>> _*4 #下划线代表最近一个表达式的值
16
除了int和float,python还支持其他的数字类型,如: Decimal和 Fraction。还有内置的复数类型complex:3+2j/3+2
Strings
>>> 'hello' #单引号
'hello'
>>> "I'm a girl" #双引号
"I'm a girl"
>>> 'I\'m not a boy' #反斜杠转义
"I'm not a boy"
>>> print("hello\n world") #\n换行
hello
world
>>> print(r"hello\n world") #r原始字符串,\n不换行
hello\n world
>>> "hello "*3+"world" # *字符串重复,+字符串连接
'hello hello hello world'
>>> word='python'
>>> word[0]
'p'
>>> word[5]
'n'
>>> word[-1]
'n'
>>> word[-2]
'o'
>>> len(word) #长度
6
>>> word[:2] #切片操作
'py'
>>> word[2:]
'thon'
>>> word[2:4]
'th'
>>> word[-2]
'o'
>>> word[-2:]
'on'
>>> word[42] #下标超过范围报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[4:42] #切片超过范围不报错
'on'
>>> word[0]='J' #字符串不能修改
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Lists
>>> cubes=[1,8,27,66] #列表
>>> cubes[0]
1
>>> cubes[-1]
66
>>> cubes[:]
[1, 8, 27, 66]
>>> cubes[-3:]
[8, 27, 66]
>>> cubes.append(343) #后面添加元素
>>> cubes
[1, 8, 27, 66, 343]
>>> cubes=cubes+[125,216] #连接
>>> cubes
[1, 8, 27, 66, 343, 125, 216]
>>> cubes*2 #重复
[1, 8, 27, 66, 343, 125, 216, 1, 8, 27, 66, 343, 125, 216]
>>>s=[1,2,3,4,5,6,7]
>>> s[2:5]=['C','D','E'] #修改
>>> s
[1, 2, 'C', 'D', 'E', 6, 7]
>>> s[2:5]=[] #修改
>>> s
[1, 2, 6, 7]
>>> s[:]=[] #修改
>>> s
[]
b
>>> s=[1,2,3,4,5,6,7]
>>> len(s) #长度
7
>>> a=[1,2]
>>> b=['c','d']
>>> s=[a,b] #二维数组
>>> s
[[1, 2], ['c', 'd']]
>>> s[1][0]
'c'