Python variable as a string

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 23 09:40:04 EDT 2013


On Fri, 23 Aug 2013 21:40:06 +1000, Jake Angulo wrote:

> Sorry this is a very basic question.

Not so much "basic" as confusing.

> I have a list *var* which after some evaluation I need to refer to *var*
> as a string.
> 
> Pseudocode:
> 
> var = ['a', 'b' , 'c' , 'd']
> adict = dict(var='string', anothervar='anotherstring')

This creates a dict with two keys, "var" and "anothervar". If you print 
it, you will get this:

{'var': 'string', 'anothervar': 'anotherstring'}

Is that what you intended? If not, what did you intend?


> anotherdict = dict()
> if <condition>:
>     anotherdict[akey] = adict['var']

I don't understand what this code has to do with your question. Your 
explanation below doesn't seem to have anything to do with the code you 
show here. You don't evaluate the list var, or test it in a truth 
context. Apart from wrapping condition in angle brackets, for no reason I 
understand, the above is perfectly fine Python code (except, of course, 
condition and akey are undefined).


> Basically im evaluating the list *var*, and if true, i want to use *var*
> as a string so that i can refer to a key-value pair in *adict *(whose
> key name is also var for convenience).

I don't understand what you are trying to accomplish, but I have two 
guesses. If you want a string "var", just type "var" in quotation marks, 
like you do above.

If you want to use the *contents* of variable var as a string, just call 
the str() function on it:

py> alist = ['a', 'b' , 'c' , 'd']
py> key = str(alist)
py> adict={}
py> adict[key] = "whatever you like"
py> adict
{"['a', 'b', 'c', 'd']": 'whatever you like'}


Or if you prefer:

py> {key: "whatever"}
{"['a', 'b', 'c', 'd']": 'whatever'}


If you want something else, you'll need to explain more carefully what 
you want.


> Or maybe i should do things differently?

Possibly. What sort of things did you have in mind? :-)



-- 
Steven



More information about the Python-list mailing list