2

Here is a sentence

"[come]and[joy]"

I want to get a text in Second "[ ]" So i'll use a

 Mid(10,14)

For getting indexnumber (10,14), I wrote next code

sentense.findall('[')[1]

But, occurred error

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

If i use the below code

 sentense.find('[')

it return just first index number of '[' = 0 How can i get a second index number of '[' = 10?

It must be not using like this sentense.find('[',1), It will be possible to search sencond, or third, any Next level

please help me

Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37
  • Possible duplicate of [Get a string after a specific substring](https://stackoverflow.com/questions/12572362/get-a-string-after-a-specific-substring) – tk421 Sep 15 '17 at 06:31

2 Answers2

0

To get the indices of all occurrences of [ in a string:

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

To extract the strings (without using 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']
John1024
  • 109,961
  • 14
  • 137
  • 171
0

The best solution to get text from second [] is to use regex.

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

If you want to use string indexes only, then you can do it as John1024 answered.

#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'
>>>

You can find more information on re module here.

Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37