When I began studying Unix, I used to be launched to the
echo command fairly early within the course of. Likewise, my preliminary Python lesson concerned the
systemout. It appeared each language proudly had a handy one-line methodology of manufacturing output and marketed it prefer it was going out of fashion.
But as soon as I turned the primary web page of intermediate classes, I met
printf, a cryptic, mysterious, and surprisingly versatile perform. In going towards the puzzling custom of hiding
printf from newbies, this text goals to introduce to the world the standard
printf perform and clarify how it may be utilized in almost any language.
A short historical past of printf
The time period
printf stands for “print formatted” and should have first appeared within the Algol 68 programming language. Since its inclusion in C,
printf has been reimplemented in C++, Java, Bash, PHP, and fairly in all probability in no matter your favourite (post-C) language occurs to be.
It’s clearly well-liked, and but many individuals appear to treat its syntax to be complicated, particularly in comparison with options comparable to
cout. For instance, here is a easy echo assertion in Bash:
Here’s the identical consequence utilizing
printf in Bash:
$ printf "%sn" hiya
But you get quite a lot of options for that added complexity, and that is precisely why
printf is effectively value studying.
The important idea behind
printf is its capacity to format its output primarily based on model data separate from the content material. For occasion, there’s a assortment of particular sequences that
printf acknowledges as particular characters. Your favourite language could have better or fewer sequences, however widespread ones embody:
n: New line
r: Carriage return
t: Horizontal tab
NNN: A particular byte with an octal worth containing one to a few digits
$ printf "t123105124110n"
In this Bash instance,
printf renders a tab character adopted by the ASCII characters assigned to a string of 4 octal values. This is terminated with the management sequence to provide a brand new line (
Attempting the identical factor with
echo produces one thing slightly extra literal:
$ printf "t123105124110n"
printf options in addition to the options of a easy
These examples comprise nothing greater than literal characters, although, and whereas they’re helpful in some conditions, they’re in all probability the least important factor about
printf. The true energy of
printf lies in format specification.
Format output with printf
Format specifiers are characters preceded by a % signal (
Common ones embody:
%f: Floating-point quantity
%o: A quantity in octal
These are placeholders in a
printf assertion, which you’ll be able to change with a worth you present some other place in your
printf assertion. Where these values are supplied depends upon the language you are utilizing and its syntax, however here is a easy instance in Java:
This, wrapped in applicable boilerplate code and executed, renders:
It will get much more attention-grabbing, although, when the content material of a variable adjustments. Suppose you need to replace your output primarily based on an ever-increasing quantity:
Compiled and run:
Processing is 1% completed.
Processing is 100% completed.
Notice that the double
% within the code resolves to a single printed
Limiting decimal locations with printf
Numbers can get complicated, and
printf gives many formatting choices. You can restrict what number of decimal locations are printed utilizing the
%f for floating-point numbers. By inserting a dot (
.) together with a limiter quantity between the % signal and the
f, you inform
printf what number of decimals to render. Here’s a easy instance written in Bash for brevity:
$ printf "%.2fn" three.141519
Similar syntax applies to different languages. Here’s an instance in C:
For three decimal locations, use
.3f, and so forth.
Adding commas to a quantity with printf
Since large numbers could be troublesome to parse, it is common to interrupt them up with a comma. You can have
printf add commas as wanted by inserting an apostrophe (
') between the % signal and the
$ printf "%'dn" 1024
$ printf "%'dn" 1024601
Add main zeros with printf
Another widespread use for
printf is to impose a selected format upon numbers in file names. For occasion, when you have 10 sequential information on a pc, the pc could kind
10.jpg earlier than
1.jpg, which might be not your intent. When writing to a file programmatically, you need to use
printf to kind the file title with main zero characters. Here’s an instance in Bash for brevity:
$ printf "000%d.jpgn" 1..10
As you’ll be able to inform from these
printf examples, together with management characters, particularly
n, could be tedious, and the syntax is comparatively complicated. This is the rationale shortcuts like
cout have been developed. However, when you use
printf each every now and then, you may get used to the syntax, and it’ll develop into second nature. I do not see any motive
printf must be your first alternative for printing statements throughout on a regular basis actions, nevertheless it’s an important device to be snug sufficient with that it will not gradual you down while you want it.
Take a while to study
printf in your language of alternative, and use it while you want it. It’s a strong device you will not remorse having at your fingertips.