Printf format string refers to a control parameter used by a class of functions in the string-processing
libraries of various programming languages. The format string is written in a simple template
language, and specifies a method for rendering an arbitrary number of varied data type parameters
into a string. This string is then by default printed on the standard output stream, but
variants exist that perform other tasks with the result, such as returning it as the value
of the function. Characters in the format string are usually copied literally into the
function's output, as is usual for templates, with the other parameters being rendered into
the resulting text in place of certain placeholders – points marked by format specifiers, which
are typically introduced by a % character, though syntax varies. The format string itself
is very often a string literal, which allows static analysis of the function call. However,
it can also be the value of a variable, which allows for dynamic formatting but also a security
vulnerability known as an uncontrolled format string exploit.
The term "printf" is due to the C language, which popularized this type of function, but
these functions predate C, and other names are used, notably "format". Printf format
strings, which provide formatted output, are complementary to scanf format strings, which
provide formatted input. In both cases these provide simple functionality and fixed format
compared to more sophisticated and flexible template engines or parsers, but are sufficient
for many purposes.
Timeline Many programming languages implement a printf
function to output a formatted string. It originated from the C programming language,
where it has a prototype similar to the following:
The string constant format provides a description of the output, with placeholders marked by
"%" escape characters, to specify both the relative location and the type of output that
the function should produce. The return value yields the number of printed characters.
FORTRAN 66 Fortran's variadic PRINT statement referenced
a non-executable FORMAT statement.
will print the following:
RED NUM 123456 EXP 1.0E 03 REAL 3.14 VAL 250
COBOL COBOL provided formatting via hierarchical
data structure specification:
...
1960s: BCPL, ALGOL 68, Multics PL/I C's variadic printf has its origins in BCPL's
writef function. ALGOL 68 Draft and Final report had the functions
inf and outf, subsequently these were revised out of the original language and replaced
with the now more familiar readf/getf and printf/putf.
Multics has a standard function called ioa_ with a wide variety of control codes. It was
based on a machine-language facility from Multics's BOS.
call ioa_;
1970s: C, Lisp
will print the following line:
Color red, number1 123456, number2 00089, hex 0xff, float 3.14, unsigned value 250.
The printf function returns the number of characters printed, or a negative value if
an output error occurs. Common Lisp has the extremely powerful format
function.
prints "Hello, World!" on the standard output stream. If the first argument is nil, format
returns the string to its caller. The first argument can also be any output stream. format
was introduced into ZetaLisp at MIT in 1978, based on the Multics ioa_, and was later adopted
into the Common Lisp standard. Scheme incorporated Common Lisp-style format in SRFi-28 and SRFi-54.
1980s: Perl, Shell Perl also has a printf function. Common Lisp
has a format function which acts according to the same principles as printf, but uses
different characters for output conversion. The GLib library contains g_print, an implementation
of printf. Some Unix systems have a printf program for
use in shell scripts; many derive this from the GNU Core Utilities suite. This can be
used instead of echo in situations where the latter is not portable. For example:
may be rewritten portably as:
1990s: PHP, Python 1995: PHP also has the printf function, with
the same specifications and usage as that in C/C++. MATLAB does not have printf, but
does have its two extensions sprintf and fprintf which use the same formatting strings. sprintf
returns a formatted string instead of producing a visual output.
1991: Python's % operator hearkens to printf's syntax when interpolating the contents of
a tuple. This operator can, for example, be used with the print function:
Version 2.6 of Python added the more versatile str.format() method:
It's easy to create a C language-like printf() function in either Python 2.x or 3.x:
2000s: Java 2004: Java supported printf from version 1.5
onwards as a member of the PrintStream class, giving it the functionality of both the printf
and fprintf functions. At the same time sprintf-like functionality was added to the String class
by adding the format(String, Object... args) method.
Unlike most other implementations, Java's implementation of printf throws an exception
on encountering a malformed format string. Format placeholders
Formatting takes place via placeholders within the format string. For example, if a program
wanted to print out a person's age, it could present the output by prefixing it with "Your
age is ". To denote that we want the integer for the age to be shown immediately after
that message, we may use the format string: "Your age is %d."
The syntax for a format placeholder is %[parameter][flags][width][.precision][length]type
Parameter can be omitted or can be:
Flags can be zero or more of:
Width specifies a minimum number of characters to output, and is typically used to pad fixed-width
fields in tabulated output, where the fields would otherwise be smaller, although it does
not cause truncation of oversized fields. A leading zero in the width value is interpreted
as the zero-padding flag mentioned above, and a negative value is treated as the positive
value in conjunction with the left-alignment "-" flag also mentioned above.
Precision usually specifies a maximum limit on the output, depending on the particular
formatting type. For floating point numeric types, it specifies the number of digits to
the right of the decimal point that the output should be rounded. For the string type, it
limits the number of characters that should be output, after which the string is truncated.
Length can be omitted or be any of:
Additionally, several platform-specific length options came to exist prior to widespread
use of the ISO C99 extensions:
ISO C99 includes the inttypes.h header file that includes a number of macros for use in
platform-independent printf coding. These need to be double-quoted, e.g. printf("%"
PRId64 "\n", t); Example macros include:
Type Type can be any of:
The width and precision formatting parameters may be omitted, or they can be a fixed number
embedded in the format string, or passed as another function argument when indicated by
an asterisk "*" in the format string. For example printf("%*d", 5, 10) will result in
" 10" being printed, with a total width of 5 characters, and printf("%.*s", 3, "abcdef")
will result in "abc" being printed. If the syntax of a conversion specification
is invalid, behavior is undefined, and can cause program termination. If there are too
few function arguments provided to supply values for all the conversion specifications
in the template string, or if the arguments are not of the correct types, the results
are also undefined. Excess arguments are ignored. In a number of cases, the undefined behavior
has led to "Format string attack" security vulnerabilities.
Some compilers, like the GNU Compiler Collection, will statically check the format strings of
printf-like functions and warn about problems. GCC will also warn about user-defined printf-style
functions if the non-standard "format" __attribute__ is applied to the function.
Risks of using field width versus explicit delimiters in tabular output
Using only field widths to provide for tabulation, as with a format like "%8d%8d%8d" for three
integers in three 8-character columns, will not guarantee that field separation will be
retained if large numbers occur in the data. Loss of field separation can easily lead to
corrupt output. In systems which encourage the use of programs as building blocks in
scripts, such corrupt data can often be forwarded into and corrupt further processing, regardless
of whether the original programmer expected the output would only be read by human eyes.
Such problems can be eliminated by including explicit delimiters, even spaces, in all tabular
output formats. Simply changing the dangerous example from before to " %7d %7d %7d" addresses
this, formatting identically until numbers become larger, but then explicitly preventing
them from becoming merged on output due to the explicitly included spaces. Similar strategies
apply to string data. Custom format placeholders
There are a few implementations of printf-like functions that allow extensions to the escape-character-based
mini-language, thus allowing the programmer to have a specific formatting function for
non-builtin types. One of the most well-known is the glibc's register_printf_function().
However, it is rarely used due to the fact that it conflicts with static format string
checking. Another is Vstr custom formatters, which allows adding multi-character format
names, and can work with static format checkers. Some applications include their own printf-like
function, and embed extensions into it. However these all tend to have the same problems that
register_printf_function() has. The Linux kernel printk function supports
a number of ways to display kernel structures using the generic %p specification, by appending
additional format characters. For example, %pI4 prints an IPV4 address in dotted-decimal
form. This allows static format string checking at the expense of full compatibility with
normal printf. Most non-C languages that have a printf-like
function work around the lack of this feature by just using the "%s" format and converting
the object to a string representation. C++ offers a notable exception, in that it has
a printf function inherited from its C history, but also has a completely different mechanism
that is preferred. Programming languages with printf
AMPL awk
Bourne shell and derivatives such as Korn shell, Bourne again shell, or Z shell
C C++
Objective-C
Clojure Common Lisp
D F#
GNU MathProg GNU Octave
G Go
Haskell J
Java Clojure
Scala
Lua Maple
Mathematica MATLAB
Mythryl OCaml
(OCaml Batteries Included provides an additional user-extensible printf)
PARI/GP PHP
Perl Python
R Ruby
Rust Tcl
Transact-SQL Vala and FileStream.printf())
See also Format
C standard library Format string attack
iostream ML
printf debugging printk
scanf Notes
^ "ASA Print Control Characters". Retrieved 12 February 2010.
^ "Final SRFis". Srfi.schemers.org. Retrieved 2014-03-17.
^ "Built-in Types — Python 3.3.4 documentation". Python Programming Language – Official Website.
Python Software Foundation. Retrieved 12 February 2014.
^ Martelli, Alex. Python Cookbook, Second Edition. Sebastopol, CA: O'Reilly Media, Inc.
p. 183. ISBN 0-596-00797-3. ^ "PrintStream". Sun Microsystems Inc. 1994.
Retrieved 18 November 2008. ^ "String". Sun Microsystems Inc. 1994. Retrieved
18 November 2008. ^ ""The GNU C Library Reference Manual", "12.12.3
Table of Output Conversions"". Gnu.org. Retrieved 2014-03-17.
^ "printf" ^ "Linux kernel Documentation/printk-formats.txt".
Git.kernel.org. Retrieved 2014-03-17. External links
C++ reference for std::fprintf gcc printf format specifications quick reference
printf: print formatted output – System Interfaces Reference, The Single UNIX® Specification,
Issue 7 from The Open Group The Formatter specification in Java 1.5
GNU Bash printf(1) builtin