Groovy: Formatted printing with printf and sprintf
The function printf
can be use to format a string and print to screen.
The function sprintf
can be used to format a string for later use.
A few examples:
def x = 66
def res = sprintf("value: %s", x) // as string
println(res)
println(sprintf("value: %d", x)) // as decimal
println(sprintf("value: %c", x)) // as character
// padding with 0
printf('%05d\n', x)
println( sprintf('%05d', x) )
// indicate location of the value
names = ['First', 'Second', 'Third', 'Fourt']
println( sprintf('%2$s %3$s %3$s %1$s', names) )
def v = 65
printf("<%s>\n", v); // <65>
printf("<%10s>\n", v); // < 65>
printf("<%-10s>\n", v); // <65 >
printf("<%c>\n", v); // <A>
printf("<%d>\n", v); // <65>
printf("<%05d>\n", v); // <00065>
timestamp: 2019-04-20T09:30:01 tags:
- printf
- sprintf