There are cases when we want to format strings which will help us to print the output in a particular format.
When we use the string.format() function it returns a formatted version of its variable number of arguments following the description given by its first argument, the so-called format string.
The format string that we get the output, is similar to those of the printf function of standard C: It is composed of regular text and directives, which control where and how each argument must be placed in the formatted string.
string.format(“s = %a”)
The string.format() syntax above contains an identifier s which is the string and the identifier a is the letter that tells how to format the argument.
There are many letters to tell how to format the argument, these are −
Now let’s consider some examples where we will run the string.format() function.
Consider the following example −
s = string.format("x = %.4f",2345) print(s)
x = 2345.0000
Now let’s consider one more example where we will print the string in a format that looks exactly similar to a date. Consider an example shown below −
d = 5; m = 11; y = 2021 date = string.format("%02d/%02d/%04d",d,m,y) print(date)