Python字符串子串操作完全指南:掌握切片、查找和提取技巧
子字符串是字符串的一部分。Python字符串提供了多种方法来创建子字符串、检查字符串是否包含特定子字符串以及获取子字符串的索引位置等。在本教程中,我们将详细介绍与子字符串相关的各种操作。
Python中的字符串子串
首先,让我们了解两种不同的创建子字符串的方法。
创建子字符串
我们可以使用字符串切片来创建子字符串。此外,还可以使用split()函数根据指定的分隔符创建子字符串列表。
s = 'My Name is Pankaj'
# create substring using slice
name = s[11:]
print(name)
# list of substrings using split
l1 = s.split()
print(l1)
输出结果:
Pankaj
['My', 'Name', 'is', 'Pankaj']

检查子字符串是否存在
我们可以使用in操作符或find()函数来检查字符串中是否存在特定的子字符串。
s = 'My Name is Pankaj'
if 'Name' in s:
print('Substring found')
if s.find('Name') != -1:
print('Substring found')

统计子字符串出现次数
我们可以使用count()函数来统计字符串中子字符串出现的次数。
s = 'My Name is Pankaj'
print('Substring count =', s.count('a'))
s = 'This Is The Best Theorem'
print('Substring count =', s.count('Th'))
Substring count = 3
Substring count = 3

查找子字符串的所有索引位置
在Python中没有内置的函数可以直接获取子字符串的所有索引列表。不过,我们可以轻松地使用find()函数自定义一个实现此功能的函数。
def find_all_indexes(input_str, substring):
l2 = []
length = len(input_str)
index = 0
while index < length:
i = input_str.find(substring, index)
if i == -1:
return l2
l2.append(i)
index = i + 1
return l2
s = 'This Is The Best Theorem'
print(find_all_indexes(s, 'Th'))

你可以从我们的GitHub代码库中查看完整的Python脚本和更多Python示例代码。