热线电话:13121318867

登录
2019-01-12 阅读量: 634
python的字符串操作

您可能还记得Python中的字符串和字符数据教程,您无法使用字符串执行此操作:

>>> s = 'foobarbaz'
>>> s[2] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

可以使用以下del命令删除列表项:

>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']

>>> del a[3]
>>> a
['foo', 'bar', 'baz', 'quux', 'corge']

修改多个列表值

如果要一次更改列表中的多个连续元素,该怎么办?Python允许使用切片分配,具有以下语法:

a[m:n] = <iterable>

同样,暂时将迭代视为列表。这种分配替换的指定切片a<iterable>

>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']

>>> a[1:4]
['bar', 'baz', 'qux']
>>> a[1:4] = [1.1, 2.2, 3.3, 4.4, 5.5]
>>> a
['foo', 1.1, 2.2, 3.3, 4.4, 5.5, 'quux', 'corge']
>>> a[1:6]
[1.1, 2.2, 3.3, 4.4, 5.5]
>>> a[1:6] = ['Bark!']
>>> a
['foo', 'Bark!', 'quux', 'corge']

插入的元素数量不必等于替换的数量。Python只是根据需要增大或缩小列表。

0.0000
7
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子