我目前正在使用查找功能,发现了一个小问题。
theres gonna be a fire here
如果我有一个句子包含“here”和“theres”,并且我使用 find() 查找“here”的索引,我会得到“theres”
我认为 find() 会像 如果这个词在那个词中:
因为它会找到单词,而不是字符串中的子字符串。
是否还有其他功能可以类似地工作?我非常频繁地使用 find(),希望在使用 string.split() 阻塞代码之前了解替代方案,然后进行迭代,直到找到与侧面索引计数器完全匹配的内容。
MainLine = str('theres gonna be a fire here')
WordtoFind = str('here')
#String_Len = MainLine.find(WordtoFind)
split_line = MainLine.split()
indexCounter = 0
for i in range (0,len(split_line)):
indexCounter += (len(split_line[i]) + 1)
if WordtoFind in split_line[i]:
#String_Len = MainLine.find(split_line[i])
String_Len = indexCounter
break
最佳答案
最好的途径是正则表达式。要查找“单词”,只需确保前导字符和结尾字符不是字母数字即可。它不使用分割,没有暴露的循环,甚至当你遇到像“这里有火”这样的奇怪句子时也能工作。 find_word 函数可能如下所示
import re
def find_word_start(word, string):
pattern = "(?<![a-zA-Z0-9])"+word+"(?![a-zA-Z0-9])"
result = re.search(pattern, string)
return result.start()
>> find_word_start("here", "There is a fire,here")
>> 16
我制作的正则表达式使用了一种称为环视的技巧,可确保单词前后的字符不是字母或数字。 https://www.regular-expressions.info/lookaround.html 。术语[a-zA-Z0-9]
是由a-z、A-Z和0-9集合中的单个字符组成的字符集。查找 python re 模块以了解有关正则表达式的更多信息。
关于python - 如何在 python 中不使用 find() 的情况下查找字符串中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53565443/