python 字符串子串
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字符串提供了各种方法来创建子字符串,检查其是否包含子字符串,子字符串的索引等。在本教程中,我们将研究与子字符串相关的各种操作。
Python字符串子字符串 (Python String Substring)
Let’s first look at two different ways to create a substring.
首先让我们看一下创建子字符串的两种不同方法。
创建一个子串 (Create a Substring)
We can create a substring using string slicing. We can use split() function to create a list of substrings based on specified delimiter.
我们可以使用字符串切片来创建子字符串 。 我们可以使用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)Output:
输出:
Pankaj
['My', 'Name', 'is', 'Pankaj']检查是否找到子字符串 (Checking if substring is found)
We can use in operator or find() function to check if substring is present in the string or not.
我们可以使用in运算符或find()函数来检查字符串中是否存在子字符串。
s = 'My Name is Pankaj'
if 'Name' in s:
print('Substring found')
if s.find('Name') != -1:
print('Substring found')Note that find() function returns the index position of the substring if it’s found, otherwise it returns -1.

注意,find()函数返回子字符串的索引位置(如果找到),否则返回-1。
子字符串出现次数 (Count of Substring Occurrence)
We can use count() function to find the number of occurrences of a substring in the string.
我们可以使用count()函数查找字符串中子字符串的出现次数。
s = 'My Name is Pankaj'
print('Substring count =', s.count('a'))
s = 'This Is The Best Theorem'
print('Substring count =', s.count('Th'))Output:
输出:
Substring count = 3
Substring count = 3查找子字符串的所有索引 (Find all indexes of substring)
There is no built-in function to get the list of all the indexes for the substring. However, we can easily define one using find() function.
没有内置函数来获取子字符串的所有索引的列表。 但是,我们可以使用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'))Output: [0, 8, 17]
输出: [0, 8, 17]
翻译自: https://www.journaldev.com/23774/python-string-substring
python 字符串子串