Python最新官方文档目前没有中文版,我用自已的语言来翻义The Python Tutorial,即意义,不是直义。所以会省略一些我认为不重要的内容,但尽量不跳过任何知识点。请对应The Python Tutoria目录来看这一系列文章。
- An Informal Introduction to Python
3.1. Using Python as a Calculator
3.1.1. Numbers
3.1.2. Strings
3.1.3. Lists
3.2. First Steps Towards Programming
##Lists
字符变量可以当成数组那样操作,下标以0开始。但并不是真正的数组。
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
>>> word[-1] # 下标可以是负数,例如-1是末尾倒数第一个。
'n'
>>> word[2:5] # 包括下标2,但不包括下标5
'tho'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'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[42:] # 双下标数据越界却不会报错
''
>>> word[0] = 'J' #word是字符串变量,值是'Python',虽然可以像数组那样通过下标索引(只读),但它不是一个真正的数组,所以并不可以给数据项赋值(非只读)。
...
TypeError: 'str' object does not support item assignment
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s) #len函数返回字符长度
34
真正的数组还可以给item(数据项)可以赋值或修改删除等操作的,且这些item可以是不同的数据类型。
>>> squares = [1, 4, 9, 16, 25] #新建一个数据项都是int类型的数组。
>>> squares
[1, 4, 9, 16, 25]
>>> squares + [49, 64, 81, 100] #list可以像string那样串联。
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
同样支持slice(切片)操作。
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E'] #修改数据项的值
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> letters[2:5] = [] #删除部分数据项
>>> letters
['a', 'b', 'f', 'g']
[]
len()同样适用于list。list的item可以是任何数据类型,甚至是list类型。
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n] #list x 包含两个item,这两个item数据类型是list。
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0] #打印x的第一个item
['a', 'b', 'c']
>>> x[0][1] #打印x的第一个item a的第二个item 'b'
'b'
index 返回第一个match到的object(即item值)的索引位置
remove 指定object(item值)来删除match到的第一个object
pop 指定索引来删除object,并且return该object
extend 加入一个list、set、元组等iterable到list中
insert 插入object到指定索引位置
append 插入到尾巴
count 计算某object值有的个数。
##First Steps Towards Programming
>>> a, b = 0, 1 #同时给a和b赋值,分别为0,1
>>> while b < 10:
... print(b) #语法要求,缩进4空格
... a, b = b, a+b #右边表达式先运算,之后把运算结果赋值到左边
...
1
1
2
3
5
8
print之后默认输出换行符,可通过end关键字指定其他字符代替默认的换行符。
>>> a, b = 0, 1
>>> while b < 1000:
... print(b, end=',') #关键字end的用法
... a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
print通过逗号“,”分隔多个输出项,字符常量需要引号引起来,变量不用。
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536