printing variables

Gary Herron gherron at islandtraining.com
Fri Oct 6 05:07:29 CEST 2006


s99999999s2003 at yahoo.com wrote:
> hi
> say i have variables like these
>
> var1 = "blah"
> var2 = "blahblah"
> var3 = "blahblahblah"
> var4 = "...."
> var5 = "..."..
>
> bcos all the variable names start with "var", is there a way to
> conveniently print those variables out...
> eg print var* ??
> i don't want to do :
>
> print var1, var2, var3, var4 ......etc...
> thanks
>
>   
If you really don't want an array (list, or tuple) of these (i.e.,
var[1], var[2], var[3], ...), then you can get at a dictionary that
contains all the local variables -- names and values -- like this:


>>> var1 = "blah"
>>> var2 = "blahblah"
>>> var3 = "blahblahblah"
>>> var4 = "...."
>>> locals()
{'var4': '....', 'var1': 'blah', 'var3': 'blahblahblah', 'var2':
'blahblah', '__builtins__': <module '__builtin__' (built-in)>,
'__file__': '/home/gherron/.startup.py', '__name__': '__main__',
'__doc__': None}

>>> for v,k in locals().items():
... if v.startswith('var'):
... print k
...
....
blah
blahblahblah
blahblah
>>>


Gary Herron




More information about the Python-list mailing list