Python程序查找字符串中子字符串出现的次数
给定一个单词列表,提取这些单词在字符串中出现的所有索引。
Input : test_str = ‘geeksforgeeks is best for geeks and cs’, test_list = [“best”, “geeks”]
Output : [2, 4]
Explanation : best and geeks occur at 2nd and 4th index respectively.
Input : test_str = ‘geeksforgeeks is best for geeks and cs’, test_list = [“best”, “geeks”, “is”]
Output : [1, 2, 4]
Explanation : is, best and geeks occur at 1st, 2nd and 4th index respectively.
方法 #1:使用列表理解 + split() + index()
在这里,我们使用 split() 执行从句子中获取单词的任务,然后使用 index() 将字符串列表中的单词匹配到提取的字符串。
Python3
# Python3 code to demonstrate working of
# Word occurrence positions in String
# Using list comprehension + split() + index()
# initializing string
test_str = 'geeksforgeeks is best for geeks and cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing list
test_list = ["best", "geeks", "cs"]
# using index() to get indices,
# list comprehension used to offer one liner
res = [test_str.split().index(ele)
for ele in test_str.split() if ele in test_list]
# printing result
print("The indices list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Word occurrence positions in String
# Using list comprehension + enumerate() + split()
# initializing string
test_str = 'geeksforgeeks is best for geeks and cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing list
test_list = ["best", "geeks", "cs"]
# using enumerate() to get indices,
# list comprehension used to offer one liner
res = [idx for idx, ele in enumerate(test_str.split()) if ele in test_list]
# printing result
print("The indices list : " + str(res))
输出
The original string is : geeksforgeeks is best for geeks and cs
The indices list : [2, 4, 6]
方法 #2:使用列表推导 + enumerate() + split()
这是可以执行此任务的另一种方式。在这个获取索引的任务中,使用 enumerate() 来完成。
蟒蛇3
# Python3 code to demonstrate working of
# Word occurrence positions in String
# Using list comprehension + enumerate() + split()
# initializing string
test_str = 'geeksforgeeks is best for geeks and cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing list
test_list = ["best", "geeks", "cs"]
# using enumerate() to get indices,
# list comprehension used to offer one liner
res = [idx for idx, ele in enumerate(test_str.split()) if ele in test_list]
# printing result
print("The indices list : " + str(res))
输出
The original string is : geeksforgeeks is best for geeks and cs
The indices list : [2, 4, 6]