You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 22:40:48