How to convert a list of strings into a list of variables

John Gordon gordon at panix.com
Thu Aug 18 18:09:43 CEST 2011


In <2ab25f69-6017-42a6-a7ef-c71bc2ee8547 at l2g2000vbn.googlegroups.com> noydb <jenn.duerr at gmail.com> writes:

> How would you convert a list of strings into a list of variables using
> the same name of the strings?

> So, ["red", "one", "maple"] into [red, one, maple]

> Thanks for any help!

If the strings and the object names are exactly the same, you could use
eval().  (Of course this assumes the objects already exist.)

  red = "this is the red object"
  one = 1
  maple = "this is the maple object"

  list_of_strings = ["red", "one", "maple"]
  list_of_variables = []

  for x in list_of_strings:
    list_of_variables.append(eval(x))

  for y in list_of_variables:
    print y

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list