这里有一句话
"[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),它可以搜索第二个,或者第三个,任何下一级
请帮帮我
发布于 2017-09-15 14:09:38
要获取字符串中所有出现的[的索引:
>>> sentence = "[come] and[joy]"
>>> [i for i,c in enumerate(sentence) if c=='[']
[0, 10]要提取字符串(不使用re):
>>> 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']发布于 2017-09-15 14:23:35
从second []获取文本的最佳解决方案是使用regex。
>>> 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上找到更多信息。
https://stackoverflow.com/questions/46232655
复制相似问题