Python截取函数

在Python中,你可以使用切片(slice)来截取字符串、列表和其他序列类型的一部分。以下是一些常见的示例:

  1. **截取字符串**:

```python

s = "Hello, World!"

substring = s[7:12] # 从索引7开始到索引12(不包括12)结束

print(substring) # 输出: World

```

  1. **使用负数索引截取**:

```python

s = "Hello, World!"

substring = s[-6:-1] # 从倒数第6个字符开始到倒数第1个字符(不包括倒数第1个字符)结束

print(substring) # 输出: World

```

  1. **截取列表**:

```python

my_list = [1, 2, 3, 4, 5]

sublist = my_list[1:4] # 截取索引1到索引4之间的元素(不包括索引4)

print(sublist) # 输出: [2, 3, 4]

```

  1. **步长截取**:

```python

s = "abcdefg"

substring = s[::2] # 从头到尾每隔一个字符截取

print(substring) # 输出: aceg

```

这些示例展示了如何在Python中使用切片操作来截取字符串、列表和其他序列类型的子集。

相关推荐
Flittly1 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling5 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook9 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风10 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风10 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm