Python中的字符串切片

Python中的字符串切片

Python中的字符串切片

  Python 切片是通过对给定字符串从头到尾分别进行切片来获取子字符串。 

  为了理解切片,我们将使用不同的方法,这里我们将介绍两种字符串切片方法,一种使用内置的 slice() 方法,另一种使用[:] 数组 slice。Python中的字符串切片是通过给定的字符串从头到尾分别切片来获取子字符串。 

Python中的字符串切片

  Python 切片可以通过两种方式完成:

  • 使用 slice() 方法
  • 使用数组切片 [:: ] 方法

  正负索引的索引跟踪器: Python 中的字符串索引和切片。在这里,反向跟踪字符串时会考虑负数。 

  推荐:如何使用Python程序Pytube库下载YouTube视频

1、使用slice()方法

  slice ()构造函数创建一个切片对象,表示由 range(start、stop、step) 指定的索引集。

  slice ()语法:

  • slice(stop)
  • slice(start, stop, step)

参数: start:对象切片开始的起始索引。stop:对象切片停止处的结束索引。step:这是一个可选参数,决定切片的每个索引之间的增量。返回类型:返回仅包含给定范围内的元素的切片对象。 

# Python program to demonstrate
# string slicing

# String slicing
String = 'ASTRING'

# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)

print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])

输出:
String slicing
AST
SR
GITA

  推荐:如何使用PIP安装Python yaml包

2、使用List/array切片[::]方法

  在Python中,索引语法可以用来代替切片对象。这是一种使用列表切片和数组切片在语法和执行方面对字符串进行切片的简单便捷的方法。开始、结束和步骤与 slice() 构造函数具有相同的机制。 

  下面我们将通过示例了解Python 中的字符串切片。

arr[start:stop]         # items start through stop-1
arr[start:]             # items start through the rest of the array
arr[:stop]              # items from the beginning through stop-1
arr[:]                  # a copy of the whole array
arr[start:stop:step]    # start through not past stop, by step

  示例1:

  在此示例中,我们将看到python 列表中的切片索引从 0 索引开始,以 2 索引结束(在 3-1=2 处停止)。

# Python program to demonstrate
# string slicing

# String slicing
String = 'PYTHONTHREE'

# Using indexing sequence
print(String[:3])

输出:PYT

  推荐:[最新版]MailPoet Pro高级插件WordPress电子邮件插件

  示例2:

Python中的字符串切片

  在这个例子中,我们将看到从 1 索引开始到 5 索引结束(在 3-1=2 处停止)的示例,跳过步骤为 2。这是Python 按字符切片字符串的一个很好的例子。

# Python program to demonstrate
# string slicing

# String slicing
String = 'PYTHONTHREE'

# Using indexing sequence
print(String[1:5:2])

输出:
YH

  示例3:

  在此示例中,我们将看到从 -1 索引开始并以 -12 索引结束(在 3-1=2 处停止)的示例,并且跳过步长为 -2。

# Python program to demonstrate
# string slicing

# String slicing
String = 'PYTHONTHREE'

# Using indexing sequence
print(String[-1:-12:-2])

输出:ERTOTP

  推荐:将日志记录添加到Python库

使用 islice()

  islice() 是 itertools 模块中定义的内置函数。它用于获取迭代器,该迭代器是任何可迭代对象的基于索引的切片。它的工作方式类似于标准切片,但返回一个迭代器。

  语法:

itertools.islice(iterable, start, stop[, step])
参数: iterable:任何可迭代序列,如列表、字符串、元组等。 start:可迭代切片开始的起始索引。stop:可迭代切片结束处的结束索引。步骤:可选参数。它指定切片的每个索引之间的间隙。返回类型:从给定的可迭代序列返回迭代器。

# Python program to demonstrate
# islice()

import itertools

# Using islice()
String = 'PYTHONTHREE'

# prints characters from 3 to 7 skipping one character.
print(''.join(itertools.islice(String, 3, 7)))
#This code is contributed by Edula Vinay Kumar Reddy

输出:
HONT

  推荐:将NumPy数组转换为csv文件

  推荐:Python使用教程


晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Python中的字符串切片

转载请保留链接:https://www.pythonthree.com/string-slices-in-python/

滚动至顶部