Programming Search⌘K

String formatting

How programs build text from values: interpolation, format strings, padding, number formats and templates.

Concepts

  • String interpolation

    String interpolation puts the values of variables or expressions into a string literal at the places of placeholders. f-strings, template literals and $"..." strings are examples.

    intro
  • Format specifiers

    A format specifier is a short code in a format string, such as %5.2f or {:>8}, that tells a format function how to show one value: its width, alignment, precision, sign and base.

    core
  • Locale-aware formatting

    Locale-aware formatting shows a number, a price or a date with the symbols and the digit groups of a language and region, so 1234.5 is 1,234.5 in English and 1.234,5 in German.

    core

Tasks

  • Format a number with fixed decimals

    Write a floating-point number with exactly n digits after the decimal point, with %.2f, toFixed, F2 or {:.2}. The function rounds the stored binary value, so 2.675 gives 2.67.

    10 languagesintro
  • Format a number with separators

    Write an integer with a comma between each group of 3 digits, as in 1,234,567, with a format option, a locale API or a short loop. The result must not change with the locale of the computer.

    10 languagesintro
  • Interpolate values into a string

    Build a sentence from values with string interpolation: a name, a count with the right plural and a computed total. Escape the literal braces, and never treat a value as a format.

    10 languagesintro
  • Pad a string

    Pad a string to a width with a fill character, on the left and on the right, with padStart, rjust, PadLeft or a format width. A string that is already wide enough does not change.

    10 languagesintro
  • Print formatted output

    Print a line of a table with a format: a name on the left in 10 columns, a count on the right in 5 and a price with 2 decimals in 8, with printf, format, println! and f-strings.

    10 languagesintro
  • Use a text template

    Fill a template that is data, not code: change $name and ${name} to values from a table and $$ to $, in one pass, with string.Template, a regular expression with a callback, or a small scanner.

    10 languagescore
  • Wrap text to a width

    Break a text into lines of at most a given width with the greedy method: put as many words as fit on a line, then start the next one. A word longer than the width gets a line of its own.

    10 languagescore