0

How would I print a list of strings as their individual variable values?

For example, take this code:

a=1
b=2
c=3
text="abc"
splittext = text.split(text)
print(splittext)

How would I get this to output 123?

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555

2 Answers2

3

You could do this using eval, but it is very dangerous:

>>> ''.join(map(lambda x : str(eval(x)),Text))
'123'

eval (perhaps they better rename it to evil, no hard feelings, simply use it as a warning) evaluates a string as if you would have coded it there yourself. So eval('a') will fetch the value of a. The problem is that a hacker could perhaps find some trick to inject arbitrary code using this, and thus hack your server, program, etc. Furthermore by accident it can perhaps change the state of your program. So a piece of advice is "Do not use it, unless you have absolutely no other choice" (which is not the case here).

Or a less dangerous variant:

>>> ''.join(map(lambda x : str(globals()[x]),Text))
'123'

in case these are global variables (you can use locals() for local variables).

This is ugly and dangerous, because you do not know in advance what a, b and c are, neither do you have much control on what part of the program can set these variables. So it can perhaps allow code injection. As is advertised in the comments on your question, you better use a dictionary for that.

Dictionary approach

A better way to do this is using a dictionary (as @Ignacio Vazquez-Abrams was saying):

>>> dic = {'a':1,'b': 2,'c':3}
>>> ''.join(map(lambda x : str(dic[x]),Text))
'123'

List instead of string

In the above we converted the content to a string using str in the lambda-expression and used ''.join to concatenate these strings. If you are however interested in an array of "results", you can drop these constructs. For instance:

>>> map(lambda x : dic[x],Text)
[1, 2, 3]

The same works for all the above examples.

EDIT

For some reason, I later catched the fact that you want to print the valuesm, this can easily be achieved using list comprehension:

for x in Text :
    print dic[x]

again you can use the same technique for the above cases.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

In case you want to print out the value of the variables named in the string you can use locals (or globals, depending on what/where you want them)

>>> a=1
>>> b=2
>>> c=3
>>> s='abc'
>>> for v in s:
...  print(locals()[v])
... 
1
2
3

or, if you use separators in the string

>>> s='a,b,c'
>>> for v in s.split(','):
...  print(locals()[v])
... 
1
2
3
Pynchia
  • 10,996
  • 5
  • 34
  • 43