Unpythonic way of printing variables in Python?
The only other way would be to use the Python 2.6+/3.x .format()
method for string formatting:
# dict must be passed by reference to .format()
print("{foo}, {bar}, {baz}").format(**locals())
Or referencing specific variables by name:
# Python 2.6
print("{0}, {1}, {2}").format(foo, bar, baz)
# Python 2.7/3.1+
print("{}, {}, {}").format(foo, bar, baz)
Using % locals()
or .format(**locals())
is not always a good idea. As example, it could be a possible security risk if the string is pulled from a localization database or could contain user input, and it mixes program logic and translation, as you will have to take care of the strings used in the program.
A good workaround is to limit the strings available. As example, I have a program that keeps some informations about a file. All data entities have a dictionary like this one:
myfile.info = {'name': "My Verbose File Name",
'source': "My Verbose File Source" }
Then, when the files are processes, I can do something like this:
for current_file in files:
print 'Processing "{name}" (from: {source}) ...'.format(**currentfile.info)
# ...
I prefer the .format()
method myself, but you can always do:
age = 99
name = "bobby"
print name, "is", age, "years old"
Produces: bobby is 99 years old
. Notice the implicit spaces.
Or, you can get real nasty:
def p(*args):
print "".join(str(x) for x in args))
p(name, " is ", age, " years old")