-1

How to choose [Andrey] and [21] from info?

info = "my name is [Andrey] and I am [21] years old"
result = ["[Andrey]", "[21]"];
Paolo
  • 20,112
  • 21
  • 72
  • 113
  • 1
    SO is about fixing _your_ Code - not solving your tasks. Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic) again and if you have questions provide your code as [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). If you encounter errors, copy and paste the error message verbatim (word for word) into your question. Providing pure "Gimme Code For Problem ...." questions are downvotet and closed fast - add your code and what you researched so we see you _trieed_ to solve it yourself – Patrick Artner Dec 02 '18 at 09:37
  • Possible duplicate of [What's the regular expression that matches a square bracket?](https://stackoverflow.com/questions/928072/whats-the-regular-expression-that-matches-a-square-bracket) – Moshe Slavin Dec 02 '18 at 09:38

2 Answers2

2

I am sure other ways would be better. But I tried this and it worked.
If you want to extract characters inside [] without knowing its position, you can use this method:
Run a for loop through string
If you find character [
append all the next characters in a string until you find ]
you can add these strings in a list to fetch result together. Here is the code.

info = "my name is [Andrey] and I am [21] years old"
s=[]    #list to collect searched result
s1=""   #elements of s
for i in range(len(info)):
    if info[i]=="[":
        while info[i+1] != "]":
            s1 += info[i+1]
            i=i+1
        s.append(s1)
        s1=""
        #make s1 empty to search for another string inside []
print s

Output will be:

['Andrey', '21']
Naazneen Jatu
  • 526
  • 9
  • 19
1

You may choose to regex method.

Or simply use list comprehension for your use case here:

>>> print([ lst[index] for index in [3,7] ])
['[Andrey]', '[21]']

But another way, You first convert your string to list and then choose by index method with the help of itemgetter:

>>> info = "my name is [Andrey] and I am [21] years old"
>>> lst = info.split()
>>> lst
['my', 'name', 'is', '[Andrey]', 'and', 'I', 'am', '[21]', 'years', 'old']
>>> from operator import itemgetter
>>> print(itemgetter(3,7)(lst))
('[Andrey]', '[21]')
Karn Kumar
  • 8,518
  • 3
  • 27
  • 53
  • if you don't know how many words in the sentence, for example the word in brackets will be like [Al Burhani Ibn kasir], and at this time how to choose this from sentence – Nurdaulet Ryspay Dec 07 '18 at 05:17