gpt4 book ai didi

python - 如何在Python中的字符串中查找确切单词的索引

转载 作者:行者123 更新时间:2023-12-04 04:47:02 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Finding the position of a word in a string

(2 个回答)


去年关闭。



word = 'laugh'    
string = 'This is laughing laugh'
index = string.find ( word )

指数是 8,应该是 17。
我用力环顾四周,却找不到答案。

最佳答案

您应该使用正则表达式(带字边界)作为 str.find返回第一次出现。然后使用 start match 的属性对象以获取起始索引。

import re

string = 'This is laughing laugh'

a = re.search(r'\b(laugh)\b', string)
print(a.start())
>> 17

您可以找到有关其工作原理的更多信息 here .

关于python - 如何在Python中的字符串中查找确切单词的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38956274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com