Someone has recently demonstrated to me that we can print variables in Python like how Perl does.
Instead of:
print("%s, %s, %s" % (foo, bar, baz))
we could do:
print("%(foo)s, %(bar)s, %(baz)s" % locals())
Is there a less hacky looking way of printing variables in Python like we do in Perl? I think the 2nd solution actually looks really good and makes code a lot more readable, but the locals() hanging around there makes it look like such a convoluted way of doing it.
Python print multiple variables To print multiple variables in Python, use the print() function. The print(*objects) is a built-in Python function that takes the *objects as multiple arguments to print each argument separated by a space.
To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")
Using closure, you can save the print statement and its parameter at the time it called. Then you can call this saved statement at any time you want later.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With