Welcome, guest | Sign In | My Account | Store | Cart

Many people are used to having printf with its format expansion. Using lambdas and pythons % expansion, this can be done in a single line. It also does not add spaces or newlines (as print does).

Python, 5 lines
1
2
3
4
5
import sys

printf = lambda fmt,*args: sys.stdout.write(fmt%args)

printf ("This is a %s of %is of possibilities of %s","test",1000,printf)

Lambdas are neat to keep code clean, especially when the code in them is used often. The ordinary print statement adds either a linefeed or a single space to the end of the line - something one not always wants.

2 comments

Bill Hallahan 10 years, 9 months ago  # | flag

The solution is clever, but obsolete today.

With python 2.7, and I believe earlier, you can do the following.

print "This is a {0} of {1}is of possibilities of {2}".format("test", 1000, something)

Single quotes work too, and also this is a general string operation, not just for printing.

text = 'This is a {0} of {1}is of possibilities of {2}'.format("test", 1000, something)

Finally, there are modifiers for the fields where strings are replaced, e.g. {0} that allows advanced formatting. Look up the documentation for string.format() for more information.

Tobias Klausmann (author) 10 years, 9 months ago  # | flag

Bill, note that this recipe is over eleven years old. Back when I wrote it, neither "".format() nor the newer additions (like file= and end= on print) existed. As such it was useful back then.

I'm well aware of the newer features and use them regularly ;)

Created by Tobias Klausmann on Wed, 6 Feb 2002 (PSF)
Python recipes (4591)
Tobias Klausmann's recipes (1)

Required Modules

Other Information and Tasks