![]() |
string to variable... or something
say I have a variable called example I want to print the contents of example, but I want to print it using its name from a string. Like so:
print "example" naturally it will print the string example and not the contents of the variable example. How do I... de-string a string if you will? |
I've never used Python in my life, but what you want might be possible if the language has some mechanism for determining attributes at run time, similar to System.Runtime.Reflection in C#.
|
How about using string concatenation via + ?
:
#!/usr/bin/python[jpowers@pandora ~]$ python string.py Hello Jason. How are you? |
Something like this maybe?
:
class Person(object):EDIT: Ah, I think I misunderstood your question. Too print the contents of a variable in a string, just use the "%s" specifier and follow it with an argument. For example: :
name = "Joe" |
In Python, there are two types of variables: locals and globals. Locals are variables defined inside functions/methods without the 'global' keyword, ones at module level are global.
Just some code now (with some other introspection to boot): :
>>> a = 1 |
hmm, I I don't think I explained what I am trying to do very well. I guess what I am asking is kind of similar to unpickling. Let me try again to explain.
joe = "this is what I want to print" bob = ["joe"] print bob[0] This would print the word "joe", but I want to actually print the value of joe which is "this is what I want to print". Is this possible? |
I think I explained that in my code. You might want to read it carefully, especially lines 3, 4 and 6.
|
Yes, free-zombie your post did explain what I was looking for.
I found out that there was a much simpler solution to the problem I was dealing with however. It seems like it is always like that with python and me, every time I do something I get hung up because I don't try the painfully simple and obvious things, I guess I just always expect it to be harder than it is. Thanks for all the helpful replies guys. |
I assume you found the evil function eval():
:
joe = "this is what I want to print" |
| All times are GMT -5. The time now is 6:00 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC