A substring is the part of a string. Python string provides various methods to create a substring, check if it contains a substring, index of substring etc. In this tutorial, we will look into various operations related to substrings.
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')
请注意,如果找到子串,find()函数将返回子串的索引位置,否则将返回-1。
子串出现次数统计
我们可以使用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
查找子串的所有索引
没有内置函数可以获取子串的所有索引列表。但是,我们可以轻松地使用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'))
输出:[0, 8, 17]
您可以从我们的GitHub存储库查看完整的Python脚本和更多Python示例。
Source:
https://www.digitalocean.com/community/tutorials/python-string-substring