Python中[:-1]与[::-1]的区别是什么?
Python中切片表达式
[:-1]和[::-1]的区别 这两个切片表达式写法相近,但功能完全不同,下面用具体例子拆解它们的作用:
[:-1]:截取序列除最后一个元素外的所有内容
切片的基础语法是[start:end:step],使用[:-1]时:
start省略,默认从序列第一个元素开始end设为-1,表示截止到序列的倒数第二个元素(切片是左闭右开区间,不包含end位置的元素)step省略,默认按正序1步长遍历
实际示例:
# 字符串示例 s = "hello world" print(s[:-1]) # 输出: "hello worl" # 列表示例 nums = [1, 2, 3, 4, 5] print(nums[:-1]) # 输出: [1, 2, 3, 4]
[::-1]:反转整个序列
使用[::-1]时:
start和end都省略,默认覆盖整个序列step设为-1,表示按倒序1步长遍历,从最后一个元素往第一个元素取
实际示例:
# 字符串反转 s = "hello world" print(s[::-1]) # 输出: "dlrow olleh" # 列表反转 nums = [1, 2, 3, 4, 5] print(nums[::-1]) # 输出: [5, 4, 3, 2, 1]
直观对比
用同一个序列快速看差异:
| 原序列 | [:-1]结果 | [::-1]结果 |
|---|---|---|
| "test" | "tes" | "tset" |
| [10,20,30] | [10,20] | [30,20,10] |
内容的提问来源于stack exchange,提问作者Heimson
相关产品推荐
相关产品推荐

