Python 查找字符串中的所有出现
Python 中的子字符串是出现在另一个字符串中的一组字符。处理子串通常很麻烦。一个这样的问题是在特定字符串中查找所有出现的子字符串。
本篇文章将讨论在 Python 中查找字符串中所有出现的子字符串的不同方法。
在 Python 中使用 string.count()
函数查找字符串中子字符串的所有出现次数
string.count()
是 Python 中的一个内置函数,它返回给定特定字符串中子字符串出现的数量或出现次数。此外,它还具有附加参数 start
和 end
来指定开始和结束位置的索引。
count()
方法遍历字符串并返回特定子字符串在字符串中出现的次数。
以下代码使用 string.count()
函数查找字符串中所有出现的子字符串。
#defining string and substring
str1 = "This dress looks good; you have good taste in clothes."
substr = "good"
#occurrence of word 'good' in whole string
count1 = str1.count(substr)
print(count1)
#occurrence of word 'good' from index 0 to 25
count2 = str1.count(substr,0,25)
print(count2)
输出:
2
1
这是一种简单的方法,适用于任何情况。此方法的唯一缺点是它不返回子字符串在字符串中出现的不同索引。
在 Python 中使用列表推导和 startswith()
查找字符串中子字符串的所有出现次数
这个方法需要两件事:列表推导和 startswith()
方法。
startswith()
函数执行获取子字符串开始索引的任务,并利用列表推导来遍历完整的目标字符串。
以下代码使用列表推导和 startswith()
来查找字符串中所有出现的子字符串。
# defining string
str1 = "This dress looks good; you have good taste in clothes."
# defining substring
substr = "good"
# printing original string
print("The original string is : " + str1)
# printing substring
print("The substring to find : " + substr)
# using list comprehension + startswith()
# All occurrences of substring in string
res = [i for i in range(len(str1)) if str1.startswith(substr, i)]
# printing result
print("The start indices of the substrings are : " + str(res))
输出:
The original string is : This dress looks good; you have good taste in clothes.
The substring to find : good
The start indices of the substrings are : [17, 34]
在 Python 中使用 re.finditer()
查找字符串中子字符串的所有出现
re.finditer()
是 Python 提供给程序员在他们的代码中使用的正则表达式库的一个函数。它有助于执行查找字符串中特定模式出现的任务。要使用此功能,我们需要先导入正则表达式库 re
。
re.finditer()
在其语法中使用了 pattern
和 string
参数。在这种情况下,模式指的是子字符串。
以下代码使用 re.finditer()
函数查找字符串中所有出现的子字符串。
import re
# defining string
str1 = "This dress looks good; you have good taste in clothes."
#defining substring
substr = "good"
print("The original string is: " + str1)
print("The substring to find: " + substr)
result = [_.start() for _ in re.finditer(substr, str1)]
print("The start indices of the substrings are : " + str(result))
输出:
The original string is: This dress looks good; you have good taste in clothes.
The substring to find: good
The start indices of the substrings are : [17, 34]
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串