2017-09-15 16 views
2

这里是一个句子[Python中] [海峡格式化]我如何才能找到下一个indexnumber使用“查找”

"[come]and[joy]" 

我想在第二"[ ]" 所以我将使用一个

文本
Mid(10,14) 

为了得到indexnumber(10,14), 我写了下面的代码

sentense.findall('[')[1] 

但是,发生错误

"AttributeError: 'str' object has no attribute 'findall' 

如果我使用下面的代码

sentense.find('[') 

它返回的只是第一个索引号“[” = 0 我怎样才能获得的第二个索引号“[” = 10?

必须不使用这样的sentense.find(“[”,1), 这将有可能sencond或第三搜索,任何一个新的水平

请帮我

+0

可能重复[获取特定子字符串后的字符串](https://stackoverflow.com/questions/12572362/get-a-string-after-a-specific-substring) – tk421

回答

0

要获得的[所有出现的字符串中的索引:

>>> sentence = "[come] and[joy]" 
>>> [i for i,c in enumerate(sentence) if c=='['] 
[0, 10] 

要提取的字符串(不重新使用):

>>> start = [i+1 for i,c in enumerate(sentence) if c=='['] 
>>> end = [i for i,c in enumerate(sentence) if c==']'] 
>>> [sentence[i:j] for i,j in zip(start, end)] 
['come', 'joy'] 
0

从第二个[]获取文本的最佳解决方案是使用正则表达式。

>>> import re 
>>> a = re.findall(r'\[.*\].*\[(.*)\]',s) 
>>> a 
['joy'] 
>>> a[0] 
'joy' 
>>> 

如果你只想使用字符串索引,那么你可以这样做,因为John1024回答。

#Get indexes of [ 
>>> b=[i for i,c in enumerate(s) if c=='['] 
>>> b 
[0, 9] 
>>> 

#Get indexes for ] 
>>> c=[i for i,c in enumerate(s) if c==']'] 
>>> c 
[5, 13] 
>>> 

#Get values 
>>> s[b[1]+1:c[1]] 
'joy' 
>>> 

你可以找到更多关于re模块here的信息。

+1

完美!谢谢 –

相关问题