在字符串中查找单词的位置

bluesky1年前 ⋅ 172 阅读

ChatGPT的回答仅作参考:

要在字符串中查找单词的位置,可以使用字符串的`find()`方法或正则表达式。

使用`find()`方法:
```python
string = "Hello, how are you?"
word = "how"
position = string.find(word)
print(position)  # 输出:7
```

使用正则表达式:
```python
import re

string = "Hello, how are you?"
word = "how"
pattern = re.compile(r'\b' + re.escape(word) + r'\b')
match = pattern.search(string)
if match:
    position = match.start()
    print(position)  # 输出:7
```

这两种方法都可以找到单词在字符串中的起始位置。`find()`方法返回的是第一个匹配的位置,而正则表达式返回的是第一个完全匹配的位置。

全部评论: 0

    相关推荐