python中对切片的理解

简介: 字符串还支持 切片。索引可以提取单个字符,切片 则提取子字符串:>>>

字符串还支持 切片。索引可以提取单个字符,切片 则提取子字符串:

>>>

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

注意,输出结果包含切片开始,但不包含切片结束。因此,s[:i] + s[i:] 总是等于 s

>>>

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

切片索引的默认值很有用;省略开始索引时,默认值为 0,省略结束索引时,默认为到字符串的结尾:


>>>

>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

还可以这样理解切片,索引指向的是字符 之间 ,第一个字符的左侧标为 0,最后一个字符的右侧标为 n ,n 是字符串长度。例如:


 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

第一行数字是字符串中索引 0…6 的位置,第二行数字是对应的负数索引位置。ij 的切片由 ij 之间所有对应的字符组成。

对于使用非负索引的切片,如果两个索引都不越界,切片长度就是起止索引之差。例如, word[1:3] 的长度是 2。

索引越界会报错:

>>>

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

但是,切片会自动处理越界索引:

>>>

>>> word[4:42]
'on'
>>> word[42:]
''
相关文章
|
3月前
|
Python
python元组切片
python元组切片
71 3
|
1月前
|
数据挖掘 C语言 索引
Python生成列表切片
Python生成列表切片
11 0
|
8月前
|
索引
python--切片,字符串操作
python--切片,字符串操作
|
3月前
|
Java Python
【Python • 字符串】巧用python字符串切片
【Python • 字符串】巧用python字符串切片
51 0
|
3月前
|
索引 Python 数据处理
【Python Numpy教程】切片和索引
【Python Numpy教程】切片和索引
【Python Numpy教程】切片和索引
|
3月前
|
存储 索引 Python
【Python基础】数据容器的切片操作和集合
【Python基础】数据容器的切片操作和集合
|
4月前
|
索引 Python
python切片操作
python切片操作
23 0
|
4月前
|
前端开发 索引 Python
Python 教程之 Numpy(7)—— 基本切片和高级索引
Python 教程之 Numpy(7)—— 基本切片和高级索引
46 1
|
4月前
|
前端开发 Shell 索引
Python(二十二)python切片的相关概念总结
首先,要注意一件事,在python中,字符串,元组,列表的取值都可以使用下标来实现。 其实切片这个用法之前在看列表和元组的时候,提到过。 说白了其实就是根据索引获取元素。只是在python中,给他起了个名字叫切片。 一:切片操作语法 一个完整的切片表达式包含两个“:”,用于分隔三个参数(start_index、end_index、step)。当只有一个“:”时,默认第三个参数step=1;当一个“:”也没有时,start_index=end_index,表示切取start_index指定的那个元素。 切片操作基本表达式: css 复制代码 object[start_index:end_in
109 0
|
5月前
|
Python
python字符串的切片与拼接案例
python字符串的切片与拼接案例

热门文章

最新文章