python - 如何在 python 中不使用 find() 的情况下查找字符串中的索引

标签 python python-3.x

我目前正在使用查找功能,发现了一个小问题。

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/

相关文章:

python - 打印整数或带 n 位小数的 float

python - 具有稀疏数据的列表比与 numpy 数组相同的数据消耗更少的内存

python - 如何从分区 DF(非唯一索引)中选择带有索引列表的数据?

python - 如何使用 python 将指针输入发送到 C++ 程序?

python - 如果值匹配,则将一个字典数组中的特定值合并到另一个字典数组中

python - 选择至少一列中的值为负数的行

python - 访问被拒绝 Django : (1045, "Access denied for user ' darth_vader' @'151.33.241.48'(使用密码:YES)")

python - 带有多表查询的SQL的Django views.py版本

python - 尽管使用线程,函数执行还是卡住了 GUI

python - 将计时器添加到赠品命令 discord.py