-3
my_str = 'I am want you'
    l = ['my_str']
    for value in l:
        print value   

I would like to fetch the value stored in my_str.

Expected output

I am want you

Vijay Anand Pandian
  • 1,027
  • 11
  • 23

3 Answers3

1

You can use eval.Otherwise use dictionary is good approach

my_string = 'I am want you'
l = ['my_string']

for value in l:
    print eval(value)

#output
I am want you
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
1

"eval" seems a better solution, but "exec" is also feasible.

>>> my_string = 'hello world'
>>> l = ['my_string']
>>> for each in l:
...     exec 'print ' + each
...     exec 'a = ' + each
...     print 'a = %s' % a
...
hello world
a = hello world

I also agree that it is an bad idea to use eval/exec for this purpose. Using dictionary might be a better way.

Lungang Fang
  • 1,427
  • 12
  • 14
1

I am not 100% sure what your intention is. But if you want to get integer values from a string in python there are some solutions.

>>> import re
>>> string1 = "498results should get"
>>> map(int, re.findall(r'\d+', string1))
[498]

Solution from jamylak

This groups all numbers with the help of a regular expression and then maps them, thus inserting them into an array.

You then just could iterate over this array

>>> arr = map(int, re.findall(r'\d+', string1)) 
>>> for num in arr:
>>>     print num
498

Edit: Yeah, seems like I misunderstood your question

Community
  • 1
  • 1
Timo Hanisch
  • 224
  • 1
  • 7