Python 字符串子串

Python 字符串提供了创建字符串的各种方法,检查它是否包含字符串,字符串的索引等 在本教程中,我们将研究与字符串相关的各种操作。

Python String 字符串

首先,让我们看看创建底层的两种不同的方式。

创建一个Substring

我们可以使用 string slicing来创建一个基于指定的分界器的字符串列表。

1s = 'My Name is Pankaj'
2
3# create substring using slice
4name = s[11:]
5print(name)
6
7# list of substrings using split
8l1 = s.split()
9print(l1)

输出:

1Pankaj
2['My', 'Name', 'is', 'Pankaj']

python string create substring using slice and split

检查是否找到底线

我们可以使用 in 操作符或 find() 函数来检查字符串是否存在。

1s = 'My Name is Pankaj'
2
3if 'Name' in s:
4    print('Substring found')
5
6if s.find('Name') != -1:
7    print('Substring found')

Note that find() function returns the index position of the substring if it's found, otherwise it returns -1. python string contains substring

Substring 事件的计数

我们可以使用 count() 函数来查找字符串中某个字符串的发生次数。

1s = 'My Name is Pankaj'
2
3print('Substring count =', s.count('a'))
4
5s = 'This Is The Best Theorem'
6print('Substring count =', s.count('Th'))

输出:

1Substring count = 3
2Substring count = 3

python string substring count

查找所有索引的 substring

没有内置的函数来获取字符串的所有索引列表,但是,我们可以使用 find() 函数轻松定义一个。

 1def find_all_indexes(input_str, substring):
 2    l2 = []
 3    length = len(input_str)
 4    index = 0
 5    while index < length:
 6        i = input_str.find(substring, index)
 7        if i == -1:
 8            return l2
 9        l2.append(i)
10        index = i + 1
11    return l2
12
13s = 'This Is The Best Theorem'
14print(find_all_indexes(s, 'Th'))

Output: [0, 8, 17] python string list of substring indexes positions

您可以从我们的 GitHub 存储库中查阅完整的 Python 脚本和更多 Python 示例。

Published At
Categories with 技术
comments powered by Disqus