VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python 简介(2)

>>> len(s) 34

参见

Text Sequence Type — str
字符串是 序列类型 的例子,它们支持这种类型共同的操作。
String Methods
字符串和Unicode字符串都支持大量的方法用于基本的转换和查找。
String Formatting
这里描述了使用 str.format() 进行字符串格式化的信息。
String Formatting Operations
这里描述了旧式的字符串格式化操作,它们在字符串和Unicode字符串是 % 操作符的左操作数时调用。

3.1.3. 列表

Python 有几个 复合 数据类型,用于表示其它的值。最通用的是 list (列表) ,它可以写作中括号之间的一列逗号分隔的值。列表的元素不必是同一类型:

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

就像字符串(以及其它所有内建的 序列 类型)一样,列表可以被索引和切片:

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[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]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

你还可以使用 append() 方法 (后面我们会看到更多关于列表的方法的内容)在列表的末尾添加新的元素:

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

也可以对切片赋值,此操作可以改变列表的尺寸,或清空它:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

内置函数 len() 同样适用于列表:

>>> letters = ['a', 'b', 'c', 'd']
>>> 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'

3.2. 编程的第一步

当然,我们可以使用 Python 完成比二加二更复杂的任务。例如,我们可以写一个生成 菲波那契 子序列的程序,如下所示:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
...
1
1
2
3
5
8

这个例子介绍了几个新功能。

Footnotes

[1] 因为 ** 的优先级高于 -,所以 -3**2 将解释为 -(3**2) 且结果为 -9。为了避免这点并得到 9,你可以使用 (-3)**2
[2] 与其它语言不同,特殊字符例如 \n 在单引号('...')和双引号("...")中具有相同的含义。两者唯一的区别是在单引号中,你不需要转义 " (但你必须转义 \' ),反之亦然。


相关教程
关于我们--广告服务--免责声明--本站帮助-友情链接--版权声明--联系我们       黑ICP备07002182号