Method sprintf()
- Method
sprintf
string
sprintf(strict_sprintf_format
format
,sprintf_args
...args
)- Description
Print formated output to string.
The
format
string is a string containing a description of how to output the data inargs
. This string should generally speaking have one %<modifiers><operator> format specifier (examples: %s, %0d, %-=20s) for each of the arguments.The following modifiers are supported:
'0'
Zero pad numbers (implies right justification).
'!'
Toggle truncation.
' '
Pad positive integers with a space.
'+'
Pad positive integers with a plus sign.
'-'
Left adjust within field size (default is right).
'|'
Centered within field size.
'='
Column mode if strings are greater than field width. Breaks between words (possibly skipping or adding spaces). Can not be used together with
'/'
.'/'
Column mode with rough line break (break at exactly field width instead of between words). Can not be used together with
'='
.'#'
Table mode, print a list of
'\n'
separated words (top-to-bottom order).'$'
Inverse table mode (left-to-right order).
'n'
(Where n is a number or *) field width specifier.
':n'
'.n'
Precision specifier.
';n'
Column width specifier.
'*'
If n is a * then next argument is used for precision/field size. The argument may either be an integer, or a modifier mapping as received by lfun::_sprintf():
"precision"
:int
|void
Precision (aka
'.n'
where n is a number)."width"
:int(0..)
|void
Field width (aka
'n'
or':n'
where n is a number)."flag_left"
:bool
|void
Indicates that the output should be left-aligned (aka
'-'
)."indent"
:int(0..)
|void
Base indentation level in number of spaces in %O-mode.
"'"
Set a pad string. ' cannot be a part of the pad string (yet).
'~'
Get pad string from argument list.
'<'
Use same argument again.
'^'
Repeat this on every line produced.
'@'
Repeat this format for each element in the argument array.
'>'
Put the string at the bottom end of column instead of top.
'_'
Set width to the length of data.
'[n]'
Select argument number n. Use * to use the next argument as selector. The arguments are numbered starting from
0
(zero) for the first argument after theformat
. Note that this only affects where the current operand is fetched.The following operators are supported:
'%'
Percent.
'b'
Signed binary integer.
'd'
Signed decimal integer.
'u'
Unsigned decimal integer.
'o'
Signed octal integer.
'x'
Lowercase signed hexadecimal integer or 8-bit string.
'X'
Uppercase signed hexadecimal integer or 8-bit string.
'c'
Character (integer). If a fieldsize has been specified this will output the low-order bytes of the integer in network (big endian) byte order. To get little endian byte order, negate the field size.
'f'
Float. (Locale dependent formatting.)
'g'
Heuristically chosen representation of float. (Locale dependent formatting.)
'G'
Like %g, but uses uppercase E for exponent.
'e'
Exponential notation float. (Locale dependent output.)
'E'
Like %e, but uses uppercase E for exponent.
'F'
Binary IEEE representation of float (%4F gives single precision, %8F gives double precision) in network (big endian) byte order. To get little endian byte order, negate the field size.
's'
String.
'q'
Quoted string. Escapes all control and non-8-bit characters, as well as the quote characters '\\' and '\"'.
'O'
Any value, debug style. Do not rely on the exact formatting; how the result looks can vary depending on locale, phase of the moon or anything else the lfun::_sprintf() method implementor wanted for debugging.
'p'
Hexadecimal representation of the memory address of the object. Integers and floats have no address, and are printed as themselves.
'H'
Binary Hollerith string. Equivalent to
sprintf("%c%s", strlen(str), str)
. Arguments (such as width etc) adjust the length-part of the format. Requires 8-bit strings.'n'
No argument. Same as
"%s"
with an empty string as argument. Note: Does take an argument array (but ignores its content) if the modifier'@'
is active.'t'
Type of the argument.
'{'
Perform the enclosed format for every element of the argument array.
'}'
Most modifiers and operators are combinable in any fashion, but some combinations may render strange results.
If an argument is an object that implements lfun::_sprintf(), that callback will be called with the operator as the first argument, and the current modifiers as the second. The callback is expected to return a string.
- Note
sprintf-style formatting is applied by many formatting functions, such write() and werror(). It is also possible to get sprintf-style compile-time argument checking by using the type-attributes sprintf_format or strict_sprintf_format in combination with sprintf_args.
- Note
Most formats are available in all versions of Pike; the exceptions are:
Format Version Availability constant Notes '*'
Pike 7.8.238 String.__HAVE_SPRINTF_STAR_MAPPING__ Support for specifying modifiers via a mapping. 'b'
Pike 0.7.62 'c'
Pike 0.7.3 Support for wide characters. 'c'
Pike 0.7.64 Support for little endian output. 'E'
Pike 0.6.38 'F'
Pike 0.6.38 'F'
Pike 7.8.242 String.__HAVE_SPRINTF_NEGATIVE_F__ Support for litte endian byte order. 'G'
Pike 0.6.38 'H'
Pike 7.7.31 'p'
Pike 7.5.4 Implemented but disabled ( #if 0
-block).'p'
Pike 8.1.14 Enabled. 'q'
Pike 7.7.28 'x'
Pike 8.1.5 Support for hex-formatting strings. 'X'
Pike 8.1.5 Support for hex-formatting strings. '[n]'
Pike 7.1.5 - Example
Pike v7.8 release 263 running Hilfe v3.5 (Incremental Pike Frontend) > sprintf("The unicode character %c has character code %04X.", 'A', 'A'); (1) Result: "The unicode character A has character code 0041." > sprintf("#%@02X is the HTML code for purple.", Image.Color.purple->rgb()); (2) Result: "#A020F0 is the HTML code for purple." > int n=4711; > sprintf("%d = hexadecimal %x = octal %o = %b binary", n, n, n, n); (3) Result: "4711 = hexadecimal 1267 = octal 11147 = 1001001100111 binary" > write(#"Formatting examples: Left adjusted [%-10d] Centered [%|10d] Right adjusted [%10d] Zero padded [%010d] ", n, n, n, n);
Formatting examples: Left adjusted [4711 ] Centered [ 4711 ] Right adjusted [ 4711] Zero padded [0000004711]
(5) Result: 142 int screen_width=70; > write("%-=*s\n", screen_width, >> "This will wordwrap the specified string within the "+ >> "specified field size, this is useful say, if you let "+ >> "users specify their screen size, then the room "+ >> "descriptions will automagically word-wrap as appropriate.\n"+ >> "slosh-n's will of course force a new-line when needed.\n");
This will wordwrap the specified string within the specified field size, this is useful say, if you let users specify their screen size, then the room descriptions will automagically word-wrap as appropriate. slosh-n's will of course force a new-line when needed.
(6) Result: 355 > write("%-=*s %-=*s\n", screen_width/2, >> "Two columns next to each other (any number of columns will "+ >> "of course work) independantly word-wrapped, can be useful.", >> screen_width/2-1, >> "The - is to specify justification, this is in addherence "+ >> "to std sprintf which defaults to right-justification, "+ >> "this version also supports centre and right justification.");
Two columns next to each other (any The - is to specify justification, number of columns will of course this is in addherence to std work) independantly word-wrapped, sprintf which defaults to can be useful. right-justification, this version also supports centre and right justification.
(7) Result: 426 > write("%-$*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output.");
Given a list of slosh-n separated 'words', this option creates a table out of them the number of columns be forced by specifying a presision. The most obvious use is for formatted ls output.
(8) Result: 312 > write("%-#*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output.");
Given a creates a by specifying a list of table out presision. slosh-n of them The most obvious separated the number of use is for 'words', columns formatted this option be forced ls output.
(9) Result: 312 > sample = ([ "align":"left", "valign":"middle" ]); (10) Result: ([ /* 2 elements */ "align":"left", "valign":"middle" ]) > write("<td%{ %s='%s'%}>\n", (array)sample);
<td valign='middle' align='left'>
(11) Result: 34 > write("Of course all the simple printf options "+ >> "are supported:\n %s: %d %x %o %c\n", >> "65 as decimal, hex, octal and a char", >> 65, 65, 65, 65);
Of course all the simple printf options are supported: 65 as decimal, hex, octal and a char: 65 41 101 A
(12) Result: 106 > write("%[0]d, %[0]x, %[0]X, %[0]o, %[0]c\n", 75);
75, 4b, 4B, 113, K
(13) Result: 19 > write("#%|*s\n#%|*s\n", screen_width, "THE END", >> ([ "width":screen_width ]), "ALTERNATIVE END");
# THE END # ALTERNATIVE END
(14) Result: 144
- See also
lfun::_sprintf(), strict_sprintf_format, sprintf_format, sprintf_args, String.__HAVE_SPRINTF_STAR_MAPPING__, String.__HAVE_SPRINTF_NEGATIVE_F__.