如何在Python中查找字符串中确切单词的索引 [英] How to find index of an exact word in a string in Python

查看:185
本文介绍了如何在Python中查找字符串中确切单词的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

索引为8,应为17. 我辛苦地环顾四周,但找不到答案.

index is 8, should be 17. I looked around hard, but could not find an answer.

推荐答案

您应该使用正则表达式(带有单词边界),因为str.find返回 first 出现的位置.然后使用match对象的start属性获取起始索引.

You should use regex (with word boundary) as str.find returns the first occurrence. Then use the start attribute of the match object to get the starting index.

import re

string = 'This is laughing laugh'

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

您可以在此处找到更多信息.

You can find more info on how it works here.

这篇关于如何在Python中查找字符串中确切单词的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆