Python运算符 - 切片

在Python中,切片运算符用于提取序列的一部分,例如字符串、列表或元组。

✏️ 语法

python
sequence[start:end:step]

在上面的代码中,sequence可以是任何可迭代对象,如字符串、列表或元组。
start是切片开始的索引(包含),end是切片结束的索引(不包含),step是每个切片之间要跳过的元素数。

📘 示例

python
# 切片字符串
string = "Hello, World!"
print(string[7:])  # 输出:World!

# 切片列表
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])  # 输出:[2, 3, 4]

# 切片元组
fruits = ("apple", "banana", "cherry", "date")
print(fruits[:3:2])  # 输出:('apple', 'cherry')

在上面的代码中,我们演示了在不同类型的序列上进行切片。