Format strings - Manhunter07/MFL GitHub Wiki

Format strings are strings containing a selection of more or less standardized placeholders. A format operation consists of two operands:

  1. A format string as the output base containing placeholder sub-strings
  2. One or more format arguments containing data that is formatted and inserted into the resulting formatted string

To format a string, use the format operator (%) and place the format argument(s) as second operand. That can be either an array (for any amount of format arguments) or a single numer or string (if only one format argument is needed). Once the format operation is invoked, any placeholders are replaced by their corresponding values provided in the format arguments.

Placeholders

The general pattern of a format placeholder is:

%[{INDEX}:][-[{MINWIDTH}]][.{PRECISION or MAXLENGTH}]{LETTER}
  • {INDEX} stands for the index of the value inside the second operand's array
  • {MINWIDTH} stands for minimum total length of the formatted argument
  • If {WIDTH} is set, - tells the program to justify the argument left- instead of right-handedly in case {WIDTH} is bigger than the length of the formatted argument
  • {PRECISION} stands for the amount of fractional digits in formatted number arguments
  • {MAXLENGTH} stands for the maximum character count in formatted string arguments after which any further text is truncated
  • {LETTER} stands for one of the format-indicating letters

Letters

Each placeholder has a distinct letter it is marked with. This letter decides about the input value-type, but also about how it is formatted as part of the resulting new string.

Letter Supported values Description
d Integer numbers Signed decimal integer number
u Integer numbers Unsigned decimal integer number
e Numbers Scientifically-notated number (using the e notation)
f Numbers Fixedly-notated number (using a static fraction digit count)
g Numbers Generally-notated number (using the shortest possible format out of scientific and fixed)
n Numbers Number (with thousand-separators)
m Numbers Money (using the current locale's currency format)
s Strings String of any length
x Integer numbers Hexadecimal integer number

Escaping % characters

In order to print the percent sign (%) to the formatted string instead of formatting an argument from the format argument list, place two percent signs after another, with no spaces in between: %%. This will result in a single percent sign for the formatted result string.

Examples

"Hello, %s!" % "James"                                       \"Hello, James"\
"%s has achieved %n points out of %d" % ["Michael", 6.7, 10] \"Michael has achieved 6.7 points out of 10"\
"%0:d in hexadecimal is 0x%0:x" % 7                          \"21 in hexadecimal is 15"\
"The project is completed by %5.3g%%" % [75.534]             \"The project is completed by  75,5%"\
⚠️ **GitHub.com Fallback** ⚠️