The Artima Developer Community
Sponsored Link

Python Answers Forum
string to variable name

2 replies on 1 page. Most recent reply: Jun 16, 2009 6:21 AM by Nanjundi T

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Gunnar Hurtig

Posts: 1
Nickname: ghurtig3
Registered: Dec, 2008

string to variable name Posted: Dec 10, 2008 10:16 PM
Reply to this message Reply
Advertisement
How does one convert a string into a variable name?

example

L=['a','b']

How would I then create, say:

a=[]
b=[]

from L?


Seun Osewa

Posts: 2
Nickname: seunosewa
Registered: Jun, 2007

Re: string to variable name Posted: Mar 20, 2009 1:17 PM
Reply to this message Reply

for var in L:
exec(var+"=[]")

Nanjundi T

Posts: 4
Nickname: nanjundi
Registered: Jun, 2009

Re: string to variable name Posted: Jun 16, 2009 6:21 AM
Reply to this message Reply

>>> class UseSetAttr:
... def __init__(self):
... l = ['a', 'b']
... for var in l:
... setattr(self, var, [])
...
>>> inst = UseSetAttr()
>>> inst.a
[]
>>> inst.b
[]
>>> #
>>> ### Or use globals ###
>>> #
...
>>> l = ['a', 'b']
>>> for var in l:
... globals()[var] = []
...
>>> a
[]
>>> b
[]

Flat View: This topic has 2 replies on 1 page
Topic: Python executable problem Previous Topic   Next Topic Topic: How to execute a long/Big http request using post method of

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use