How to choose
[Andrey]
and [21]
from info
?
info = "my name is [Andrey] and I am [21] years old"
result = ["[Andrey]", "[21]"];
How to choose
[Andrey]
and [21]
from info
?
info = "my name is [Andrey] and I am [21] years old"
result = ["[Andrey]", "[21]"];
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']
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]')