python求字符串中单词出现的索引
时间: 2024-03-10 19:46:56 浏览: 94
可以使用Python中的split()函数来分割字符串,然后使用enumerate()函数来遍历每个单词,并记录它们出现的索引位置。下面是一个例子:
```python
string = "Hello world, how are you today?"
# 使用split()函数分割字符串
words = string.split()
# 遍历每个单词,并记录它们出现的索引位置
for index, word in enumerate(words):
print(f"{word} appears at index {index}")
```
输出结果如下:
```
Hello appears at index 0
world, appears at index 1
how appears at index 2
are appears at index 3
you appears at index 4
today? appears at index 5
```
相关问题
python 检测字符串指定单词所有索引,但是指定单词在字符串中两边不能有其他字母 例:字符串:"as,a" 寻找:"a" 输出:"3"
要在Python中检测字符串中指定单词的所有索引,并且确保指定单词在字符串中两边不能有其他字母,可以使用正则表达式(`re`模块)来实现。以下是一个示例代码:
```python
import re
def find_word_indices(text, word):
# 使用正则表达式匹配单词,确保两边没有其他字母
pattern = r'\b{}\b'.format(re.escape(word))
matches = re.finditer(pattern, text)
# 提取匹配的起始索引
indices = [match.start() for match in matches]
return indices
# 示例字符串和单词
text = "as,a"
word = "a"
# 查找索引
indices = find_word_indices(text, word)
# 输出结果
print(indices)
```
在这个示例中:
1. `re.escape(word)` 用于转义单词中的特殊字符,确保正则表达式的正确性。
2. `\b` 是正则表达式中的单词边界,确保匹配的是完整的单词,而不是单词的一部分。
3. `re.finditer` 返回一个迭代器,包含所有匹配的 `Match` 对象。
4. 使用列表推导式提取所有匹配的起始索引。
运行上述代码,输出结果将是:
```
[3]
```
Python字符串查找单词位置
在Python中,你可以使用内置的`str.index()`或`str.find()`方法来查找单词在字符串中的位置。这两个方法都会返回指定字符或子串第一次出现的位置索引,如果找不到则会抛出异常。
1. `index()`方法:
```python
word_position = my_string.index(word)
```
如果单词在字符串中存在,这将返回单词的第一个字符的索引;如果不存在,则会引发`ValueError`。
2. `find()`方法:
```python
if my_string.find(word) != -1:
word_position = my_string.find(word)
else:
word_position = None
```
这个方法不会抛出异常,而是返回 `-1` 表示未找到,否则返回的是单词的起始索引。
例如,如果你想找出"hello"在"Hello, world! How are you?"中的位置,可以这样做:
```python
my_string = "Hello, world! How are you?"
word = "world"
position = my_string.lower().find(word.lower()) # 确保忽略大小写
if position != -1:
print(f"'{word}' 的位置是 {position}")
else:
print(f"'{word}' 没有在字符串中找到")
```
注意这里先将字符串和单词都转换成小写再查找,以便在比较时不考虑大小写差异。
阅读全文
相关推荐















