ActiveState Code

Recipe 112546: printf in a single lambda


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
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)

Discussion

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.

Sign in to comment