Strings, as we all know, are our primary way of interacting with the end user. Whether presented in a message box or simply directed to the Tcl shell, they need to be as fluid as possible, in the values they present. To accomplish this, Tcl provides the format
command. This command allows us to format a string with variable substitution in the same manner as the ANSI C sprintf
procedure. The format
command is as follows:
format string argument argument argument…
The format
command accepts a string containing the value to be formatted as well as %
conversion specifiers. The arguments contain the values to be substituted into the final string. Each conversion specifier may contain up to six sections—an XPG2 position specifier, a set of flags, minimum field width, a numeric precision specifier, size modifier, and a conversion character. The conversion specifiers are as follows:
There are three differences between the Tcl format and the ANSI C sprintf
procedure:
%p
and %n
conversion switches are not supported. %
conversion for %c
only accepts an integer value.In the following example, we format a long date string for output on the command line. Return values from the commands are provided for clarity. Enter the following command:
% set month May
May
% set weekday Friday
Friday
% set day 5
5
% set extension th
th
%set year 2010
2010
%puts [format "Today is %s, %s %d%s %d" $weekday $month $day $extension
$year]
Today is Friday, May 5th 2010
18.227.190.211