English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python 基础教程

Python 流程控制

Função do Python

Tipos de Dados do Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

Python slice() 使用方法及示例

Python built-in functions

slice()函数返回一个slice对象,该对象可用于对字符串,列表,元组等进行切片。

slice对象用于切片给定的序列(字符串字节元组列表,

slice()的语法为:

slice(start, stop, step)

slice()参数

slice() 可以采用三个参数:

  • start(可选) -对象切片开始的起始整数。如果未提供,则默认为None。

  • stop-整数,直到切片发生。切片在索引stop-1(最后一个元素)停止

  • step(可选) -整数值,用于确定切片时每个索引之间的增量。如果未提供,则默认为None。

Example1:创建切片对象

# 包含索引 (0, 1, 2)
result1 = slice(3)
print(result1)
# 包含索引  (1, 3)
result2 = slice(1, 5, 2)
print(slice(1, 5, 2))

Output result

slice(None, 3, None)
slice(1, 5, 2)

在这里,result1和result2是切片对象。

现在我们了解了slice对象,让我们看看如何从slice对象获取子字符串,子列表,子元组等。

Example2:使用切片对象获取子字符串

# 程序从给定字符串获取子字符串 
py_string = 'Python'
# stop = 3
# 包含 0, 1 and 2 Index
slice_object = slice(3) 
print(py_string[slice_object])  # Pyt
# start = 1, stop = 6, step = 2
#  Include 1, 3 and 5 Index
slice_object = slice(1, 6, 2)
print(py_string[slice_object])  # yhn

Output result

Pyt
yhn

Example3: Use negative index to get substrings

py_string = 'Python'
# start = -1, stop = -4, step = -1
#  Include index -1, -2 and -3
slice_object = slice(-1, -4, -1)
print(py_string[slice_object])  # noh

Output result

noh

Example4: Get sublists and sub-tuples

py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')
#  Include index 0, 1 and 2
slice_object = slice(3)
print(py_list[slice_object])  # ['P', 'y', 't']
#  Include index 1 and 3
slice_object = slice(1, 5, 2)
print(py_tuple[slice_object])  # ('y', 'h')

Output result

['P', 'y', 't']
('y', 'h')

Example5: Use negative index to get sublists and sub-tuples

py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')
#  Include index -1, -2 and -3
slice_object = slice(-1, -4, -1) 
print(py_list[slice_object])  # ['n', 'o', 'h']
#  Include index -1 and -3
slice_object = slice(-1, -5, -2)
print(py_tuple[slice_object])  # ('n', 'h')

Output result

['n', 'o', 'h']
('n', 'h')

Example6: Use index syntax for slicing

The slice object can be replaced with Python's index syntax.

You can use the following syntax alternately for slicing:

obj[start:stop:step]

For example,

py_string = 'Python'
#  Include index 0, 1 and 2
print(py_string[0:3))  # Pyt
#  Include index  1 and 3
print(py_string[1:5:2))  # yh

Output result

Pyt
yh

Python built-in functions