Lea*_*ava 2 python regex search python-2.7
我的任务
我正在尝试使用正则表达式查找出现在字符串中的单词的位置
码
import re
# A random string
mystr = "there not what is jake can do for you ask what you play do for spare jake".upper()
match = re.search(r"[^a-zA-Z](jake)[^a-zA-Z]", mystr)
print match.start(1)
Run Code Online (Sandbox Code Playgroud)
输出量
18
Run Code Online (Sandbox Code Playgroud)
预期产量
我希望我的输出包含字符串的位置jake:
5, 17
Run Code Online (Sandbox Code Playgroud)
编辑:为了澄清,我正在尝试确定单词的位置。我相信我所做的就是找到索引,并且不确定如何使其按预期工作
要获取jake输入字符串中搜索字符串的“常规”位置,请使用以下方法:
mystr = "there not what is jake can do for you ask what you play do for spare jake"
search_str = 'jake'
result = [i+1 for i,w in enumerate(mystr.split()) if w.lower() == search_str]
print(result)
Run Code Online (Sandbox Code Playgroud)
输出:
[5, 17]
Run Code Online (Sandbox Code Playgroud)
enumerate(mystr.split()) -获取枚举对象(带有位置/索引的项目对)
w.lower() == search_str -如果单词等于搜索字符串
| 归档时间: |
|
| 查看次数: |
823 次 |
| 最近记录: |