In this cheat sheet I’ll show all the examples using Perl, but at first it might help to see one example using both Perl and Java. Therefore, here’s a simple Perl printf example to get things started:
printf
, printf(DQthe %s jumped over the %s, %d timesDQ, DQcowDQ, DQmoonDQ, 2); ,
And here are three different Java printf examples, using different string formatting methods that are available to you in the Java programming language:
, System.out.format(DQthe %s jumped over the %s, %d timesDQ, DQcowDQ, DQmoonDQ, 2); , System.err.format(DQthe %s jumped over the %s, %d timesDQ, DQcowDQ, DQmoonDQ, 2); , String result = String.format(DQthe %s jumped over the %s, %d timesDQ, DQcowDQ, DQmoonDQ, 2); ,
As you can see in that last String.format example, that line of code doesn’t print any output, while the first line prints to standard output, and the second line prints to standard error.
String.format
In the remainder of this document I’ll use Perl examples, but again, the actual format specifier strings can be used in many different languages.
Here’s a quick summary of the available printf format specifiers:
The %3d specifier is used with integers, and means a minimum width of three spaces, which, by default, will be right-justified:
%3d
To left-justify integer output with printf, just add a minus sign (-) after the % symbol, like this:
-
%
To zero-fill your printf integer output, just add a zero (0) after the % symbol, like this:
0
As a summary of printf integer formatting, here’s a little collection of integer formatting examples. Several different options are shown, including a minimum width specification, left-justified, zero-filled, and also a plus sign for positive numbers.
Here are several examples showing how to format floating-point numbers with printf:
Here are several examples that show how to format string output with printf:
The following character sequences have a special meaning when used as printf format specifiers:
As you can see from that last example, because the backslash character itself is treated specially, you have to print two backslash characters in a row to get one backslash character to appear in your output.
Here are a few examples of how to use these special characters: