Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpythonic way of printing variables in Python?

Tags:

python

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.

like image 738
Ish Avatar asked Aug 20 '10 20:08

Ish


People also ask

How do you print 3 variables in Python?

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.

How do you print two variables on the same line in Python 3?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How does Python store printed value?

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.


1 Answers

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)    
like image 79
jathanism Avatar answered Sep 21 '22 10:09

jathanism