本文共 2202 字,大约阅读时间需要 7 分钟。
To retrieve the index of all the occurrences of a word in the string (say a statement), Python, like most of the programming languages supports the regular expression module as a built-in module. Or if we don't want the overhead of using the regular expressions, we could also use the str.index() in an iteration to get the index and also using the comprehension.
为了检索字符串中某个单词所有出现的索引 (例如一条语句),Python与大多数编程语言一样,将正则表达式模块作为内置模块来支持。 或者,如果我们不想使用正则表达式的开销,我们也可以在迭代中使用str.index()来获取索引,也可以使用comprehension 。
Example:
例:
The below example, explains the usage of the regex module's (re) method finditer() which takes the 'word' or substring to be searched for and the sentence in which the 'word' shall be searched, as the argument.
以下示例说明了正则表达式模块的(re)方法finditer()的用法,该方法以要搜索的“单词”或子字符串以及应搜索“单词”的句子作为参数。
The output of the below example is the start index and end index of the word 'to' in the sentence.
以下示例的输出是句子中单词“ to”的开始索引和结束索引。
Code:
码:
# importing the moduleimport re# sentence and word to be foundsentence = "This is a sample sentence to search for include help to search all occurrences"word = "to"# logicfor match in re.finditer(word, sentence): print("match found from {} to {}".format(match.start(), match.end()))
Output
输出量
match found from 26 to 28match found from 53 to 55
Python:
Python:
def using_str_index (word, sentence): index = 0; while index < len(sentence): index = sentence.find(word, index) if index == -1: break print('{} found at {}'.format(word, index)) index += len(word)if __name__ == '__main__': sentence = "This is a sample sentence to search for include help to search all occurrences" word = "to" using_str_index(word, sentence)
Output
输出量
to found at 26to found at 53
Code:
码:
def using_comprehension(word, sentence): print([n for n in range(len(sentence)) if sentence.find(word, n) == n])if __name__== "__main__": sentence = "This is a sample sentence to search for include help to search all occurrences" word = "to" using_comprehension(word, sentence)
Output
输出量
[26, 53]
翻译自:
转载地址:http://ikxzd.baihongyu.com/