Slice
一句话解释
slice extracts 部分 的 序列 using [开始:停止:步骤] 语法.
用大白话说
slice extracts sub-序列从 列表, 字符串, tuple, or other 序列. 语法是 sequence[start:stop:step]:
开始— the beginning index (inclusive, default 0)停止— the ending index (exclusive, default len)步骤— the stride (default 1)
All three are optional. s[:] copies the whole sequence. s[::-1] reverses it. Negative indices count from the end. Slicing always returns a new object — it never modifies the original.
Slicing is one of Python's most powerful features. It works on any sequence type and is very efficient for strings and lists.
示例
python
s = "Hello, World!"
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(s[0:5]) # Hello
print(s[7:]) # World!
print(s[:5]) # Hello
print(s[::-1]) # !dlroW ,olleH (reversed)
print(nums[2:8]) # [2, 3, 4, 5, 6, 7]
print(nums[::2]) # [0, 2, 4, 6, 8] (every other)
print(nums[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]Slicing 使用 [开始:停止:步骤] extracts subsequences. 负 索引 数量 从 端; 步骤 controls stride.
常见混淆
容易混淆的对象: 索引
关键区别: 索引 (s[i]) accesses 单个 元素. slice (s[i:j]) extracts sub-序列. Indexing 返回 one 项; slicing 返回 新 序列 的 项.
相关术语
相关资源
相关课程
- 列表
列表 slicing.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。