Unpythonic way to print variables in Python?

Someone recently demonstrated to me that we can print variables in Python, like Perl does.

Instead:

print("%s, %s, %s" % (foo, bar, baz)) 

we could do:

 print("%(foo)s, %(bar)s, %(baz)s" % locals()) 

Is there a less dangerous way to print variables in Python, like in Perl? I think the second solution really looks really good and makes the code much more readable, but the locales () hanging around make it look like such a confusing way to do this.

+7
python
source share
5 answers

The only other way is to use the Python .format() method. 6 + / 3.x .format() to format the strings:

 # dict must be passed by reference to .format() print("{foo}, {bar}, {baz}").format(**locals()) 

Or links to 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) 
+10
source share

Using % locals() or .format(**locals()) not always a good idea. As an example, this could be a possible security risk if the string is retrieved from the localization database or it may contain user input and it mixes the program logic and translation, since you have to take care of the strings used in the program.

A good workaround is to limit the available rows. As an example, I have a program that stores some information about a file. All data objects have a dictionary like this:

 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) # ... 
+5
source share

I prefer the .format() method myself, but you can always:

 age = 99 name = "bobby" print name, "is", age, "years old" 

Manufactured by: bobby is 99 years old . Note the implicit spaces.

Or you can become really nasty:

 def p(*args): print "".join(str(x) for x in args)) p(name, " is ", age, " years old") 
+2
source share

Answer: no, the syntax for strings in Python does not include Perl-style variable replacement (or Ruby, for that matter). Using โ€ฆ % locals() about the same as you are going to.

+1
source share

Starting with Python 3.6, you can get what you wanted.

 >>> name = "world" >>> print(f'hello {name}') hello world 

note the line prefix f above

+1
source share

All Articles